2012-08-06 181 views
2

在我看来,我正在测试以查看是否存在某些记录。如果他们这样做,我遍历它们并显示每一个。但是,如果这些记录不存在,我想要显示一条消息。这里是我的观点代码:忽略其他语句

 <% 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'语句完全被忽略。我试图修改'如果'的台,但无济于事。我想:

<% unless current_user.lineups.nil? %> 

除了:

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

我在我的智慧在这里结束。任何和所有的输入将不胜感激。

+1

'else'被忽略的原因是'lineups'是一个空数组,而空数组是* thruthy *。换句话说,它永远不会到达'else',因为'if []'评估为'true'。以下任一答案都可以解决您的问题。 – Mischa 2012-08-06 09:32:13

回答

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 2012-08-06 09:49:21

5

空数组不为零,尝试使用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回答