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

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

    That code can be shortened to:

    <%= @messages.empty? ? 'You have no messages.' : @messages.collect { |msg| formatted_msg(msg) }.join(msg_delimiter) %>
    

    Comments:

    formatted_msg() - helper method which adds formatting to the message

    msg_delimiter - variable containing delimiter like "\n" or "
    "

    BTW I'd suggest to use empty? method instead of blank? for checking an array, because a) its name is more concise :) and b) blank? is an ActiveSupport extension method which won't work outside Rails.

提交回复
热议问题