Search code examples
ruby-on-railsrhomobile

How to show if rhomobile array is empty


I have a bit of code in RhoMobile that shows results of a search. I want to display a message if no results are found but as a Ruby n00b I'm not getting the message I want output.

<ul data-role="listview">
   <% @employees.each do |employee| %>

     <li>
       <a href="<%= url_for :action => :show, :id => employee.object %>">
         <%= employee.name %>
       </a>
     </li>

   <% end %>
   <% "<li>No results found</li>" if @employees.empty? %>
</ul>

How to fix this?


Solution

  • You're missing the =, it should be:

    <%= "<li>No results found</li>" if @employees.empty? %>
    

    Though that might not work either because the string isn't marked as HTML safe. That said, it's probably best to wrap everything in a conditional to make it more clear and avoid having HTML in a string:

    <ul data-role="listview">
      <% if @employees.any? %>
        <% @employees.each do |employee| %>
          <li>
            <%= link_to employee.name, {:action => :show, :id => employee.object} %>
          </li>
        <% end %>
      <% else %>
        <li>No results found</li>
      <% end %>
    </ul>
    

    I've also replaced your hand-coded link with a call to link_to.