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

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

    You could split up your two cases into different templates: one if messages exist and one if no message exist. In the controller action (MessagesController#index probably), add as the last statement:

    render :action => 'index_empty' if @messages.blank?
    

    If there are no messages, it'll display app/views/messages/index_empty.html.erb. If there are messages, it'll fall through and display app/views/messages/index.html.erb as usual.

    If you need this in more than just one action, you can nicely refactor it into a helper method like the following (untested):

    def render_action_or_empty (collection, options = {})
        template = params[:template] || "#{params[:controller]}/#{params[:action]}"
        template << '_empty' if collection.blank?
        render options.reverse_merge { :template => template }
    end
    

    With this, you just need to put render_action_or_empty(@var) at the end of any controller action and it'll display either the 'action' template or the 'action_empty' template if your collection is empty. It should also be easy to make this work with partials instead of action templates.

提交回复
热议问题