else语句被忽略了

时间:2012-08-06 09:19:18

标签: ruby-on-rails ruby-on-rails-3

在我看来,我正在测试是否存在某些记录。如果他们这样做,我会迭代它们并显示每一个。但是,如果这些记录不存在,我想要显示一条消息。以下是我认为的代码:

      <% 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? ) %>

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

3 个答案:

答案 0 :(得分:5)

空数组不是零,请尝试使用any?empty?

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

答案 1 :(得分: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 %>

它会检查阵容数组是空的还是两个都没有。

答案 2 :(得分: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回答