Home > Enterprise >  What's the difference between the two ways of message rendering in Rails?
What's the difference between the two ways of message rendering in Rails?

Time:03-16

I copied an existing rails repo, but I found two ways of rendering the message to View files in different web pages.

This is the first one, which can render the "notice" or "alert" in the controller to the web page.

<% flash.each do |type, msg| %>
  <div>
    <%= msg %>
  </div>
<% end %>

This is the second one, and I have no occasion to trigger it.

<% if @task.errors.present? %>
        <ol>
        <% @task.errors.each do |error, message| %>
          <li>WARNING: <%= "#{error.capitalize}  #{message}" %>
           </li>
           <% end %>
       </ol>
<% end %>

I wonder what is the essential difference between them? Can they replace each other?

CodePudding user response:

I wonder what is the essential difference between them?

These are two completely different concepts.

The first is iterating through the flash. This is basically just a simple cookie based store used to pass primatives such as strings, hashes or arrays to the next request. The flash is typically used when displaying a message to the user after redirecting.

For example:

def deny_access
  flash[:alert] = "You must be signed in."
  redirect_to new_session_path
end

You can also set flash messages for the current request by using flash.now. The flash is purged from old messages after every request. The flash is typcially used as a kind of system wide announcement system and displayed as a banner on the top of the page.

The second is iterating (badly) through the instance of ActiveModel::Errors attached to a specific instance of a model. This is a collection of validation errors that gets filled when .valid? is called (usually indirectly) on a model instance.

You use this when displaying the validation errors of a model in the current request cycle. Typically on the top of a form or inline by the corresponding input.

Since this data is just stored in memory in an instance variable it does not persist across redirects.

Can they replace each other?

No - not really. Both are used to provide user feedback but are very different tools to solve different jobs. Doesn't really stop some noobs from trying though.

See:

  • Related