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

后端 未结 10 1061
花落未央
花落未央 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:05

    You can create some custom helper. The following one is just an example.

    # application_helper.html.erb
    def unless_empty(collection, message = "You have no messages", &block)
      if collection.empty?
        concat(message)
      else
        concat(capture(&block))
      end
    end
    
    # view.html.erb
    <% unless_empty @messages do %>
      <%# code or partial to dispaly the message %>
    <% end %>
    

提交回复
热议问题