2012-08-06 3 views
2

제 생각에 특정 레코드가 있는지 테스트하고 있습니다. 만약 그렇다면, 나는 그들을 반복하여 각각을 보여줍니다. 그러나이 레코드가 없으면 메시지를 표시하고 싶습니다. 내보기의 코드는 다음과 같습니다.else 문을 무시했습니다.

 <% if current_user.lineups %> 
     <% for lineup in current_user.lineups do %> 
      <li><%= link_to "#{lineup.course.cl} #{lineup.course.cn}", index_path %></li> 
     <% end %> 
     <% else %> 
     <li><%= link_to "You have no courses", index_path %></li> 
     <% end %> 

이제 레코드가 존재하면 반복이 제대로 작동합니다. 적절한 레코드를 만들 때마다이 코드는 놀랍게 작동하고 반복되는 각 레코드에 대한 링크를 만듭니다. 그러나 레코드가 없으면 아무 것도 표시되지 않습니다. 'else'문은 완전히 무시됩니다. 나는 'if'시합을 수정하려했지만 아무 소용이 없었다. 나는 시도 :

<% unless current_user.lineups.nil? %> 

뿐만 아니라 내 기지에서

<% if !(current_user.lineups.nil?) %> 

나는 끝 여기. 모든 입력이 감사하겠습니다.

+1

'else'가 "무시"된 이유는'lineups'은 빈 배열이고 빈 배열은 * thruthy *입니다. 즉, if []가 'true'로 평가되기 때문에 절대로 else에 도달하지 않습니다. 아래의 답변 중 하나를 선택하면 문제가 해결됩니다. – Mischa

답변

2

는이 시도 사용하려고 당신의 if 문

<% if current_user.lineups.blank? %> 
    <li><%= link_to "You have no courses", index_path %></li> 
<% else %> 
    <% for lineup in current_user.lineups do %> 
     <li><%= link_to "#{lineup.course.cl} #{lineup.course.cn}", index_path %></li> 
    <% end %> 
<% end %> 

가 배열이 비어 있거나 둘 다의 경우 전무 라인업을 확인합니다.

+0

빙고. i.imgur.com/lWPdJ.png – flyingarmadillo

5

빈 배열이 nil이 아닌, any? 또는 empty?

<% if current_user.lineups.any? %> 
    ... 
<% else %> 
    <li><%= link_to "You have no courses", index_path %></li> 
<% end %> 
2

당신은

if current_user.lineups.present? # true if any records exist i.e not nil and empty 
    # do if records exist 
else 
    # do if no records exist 
end 

선물을 시도 할 수 있습니다? 그냥 공백이 아닙니다 (!)?

필요한 코드 배치에 따라 blank? 또는 present?을 사용할 수 있습니다. 사용하는 경우 blank? @abhas로 가십시오.

관련 문제