Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

else statement ignored

In my view, I am testing to see if certain records exist. If they do, I iterate over them and display each one. If these records do not exist, however, I want a message to be displayed. Here is the code from my view:

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

Now, the iteration works just fine when the records exist. Whenever I create the proper records, this code works marvelously and creates a link for each record that is iterated over. However, If no records exists, nothing is displayed. The 'else' statement is completely ignored. I tried amending the 'if' stament but to no avail. I tried:

<% unless current_user.lineups.nil? %>

As well as:

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

I am at my wits end here. Any and all input would be appreciated.

like image 357
flyingarmadillo Avatar asked Mar 27 '26 15:03

flyingarmadillo


1 Answers

Empty array is not nil, try to use any? or empty?

<% if current_user.lineups.any? %>
  ...
<% else %>
  <li><%= link_to "You have no courses", index_path %></li>
<% end %>
like image 112
dimuch Avatar answered Mar 29 '26 04:03

dimuch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!