Rails: An elegant way to display a message when there are no elements in database

后端 未结 10 1060
花落未央
花落未央 2020-12-04 09:51

I realized that I\'m writing a lot of code similar to this one:

<% unless @messages.blank? %>
  <% @messages.each do |message|  %>
    <%# cod         


        
10条回答
  •  自闭症患者
    2020-12-04 10:26

    As a note, you may as well just iterate over an empty array if you're looking for efficiency of expression:

    <% @messages.each do |message|  %>
      <%# code or partial to dispaly the message %>
    <% end %>
    <% if (@messages.blank?) %>
      You have no messages.
    <% end %>
    

    While this does not handle @messages being nil, it should work for most situations. Introducing irregular extensions to what should be a routine view is probably complicating an otherwise simple thing.

    What might be a better approach is to define a partial and a helper to render "empty" sections if these are reasonably complex:

    <% render_each(:message) do |message|  %>
      <%# code or partial to dispaly the message %>
    <% end %>
    
    # common/empty/_messages.erb
    You have no messages.
    

    Where you might define this as:

    def render_each(item, &block)
      plural = "#{item.to_s.pluralize}"
      items = instance_variable_get("@#{plural}")
      if (items.blank?)
        render(:partial => "common/empty/#{plural}")
      else
        items.each(&block)
      end
    end
    

提交回复
热议问题