GoodGets
GoodGets

Reputation: 1849

Is there a way to make the flash[:notice] appear above, or before, the flash[:error]?

So, I'd like to be able to display both a flash[:notice] and a flash[:error] on the same action, but I'd like for the :notice to always be displayed above (or before) the error. Is there a way to do this?

In my controller, I thought I could just code the flash[:error] before the flash[:notice], so that rails will display it correctly, and it does a vast majority of the time. But every now and then they are randomly switched, and I can't seem to figure out why. So, how can I ensure that a flash[:notice] is always displayed above an :error ?

Edit: Thanks to Ben's and Ryan's advice, I've now just set up conditionals in my layout/application file.

    <% if flash[:notice] %>
        <div id="flash_notice"><%= flash[:notice] %></div>
    <% end %>

    <% if flash[:error] %>
        <div id="flash_error"><%= flash[:error] %></div>
    <% end %>

I'm pretty satisfied with this, but maybe there's an even better way?

Edit #2: Yes, there is. Ben added it to his answer below. Thanks again Mr. Ben.

Upvotes: 0

Views: 2147

Answers (3)

Ben
Ben

Reputation: 6965

The order of display simply depends on your view code. If you do this in your controller:

flash[:notice] = "Notice me"
flash[:error] = "BAAAAADDDD"

And this in your view:

<p><%= flash[:notice] %></p>
<p><%= flash[:error] %></p>

the :notice will always appear first.

Try this for a more elegant approach. The order you define in the array is the order they'll appear in:

<% [:error, :notice].each do |condition| %>
  <%= "<p class='#{condition.to_s}'>#{flash[condition]}</p>" if flash.has_key?(condition) %>
<% end %>

Upvotes: 4

Ryan Bigg
Ryan Bigg

Reputation: 107728

I would make this a comment but it doesn't do multi-lined code snippets very well. They're probably "randomly switched" because you're using it like this:

  <% flash.each do |k, v| %>
    <div id='flash_<%= k %>'><%= v %></div>
  <% end %>

In 1.8 hash keys are unordered and because flash is a Hash, you'll get these output in whatever order Ruby feels like at the time. As Ben suggested, putting them in the "correct" order manually would help.

Upvotes: 1

Salil
Salil

Reputation: 47482

Always nil your notice and error object.

<% if flash[:notice] %><p><%= flash[:notice] %><% flash[:notice]=nil %></p><% end %>
<% if flash[:error] %><p><%= flash[:error] %><% flash[:error] =nil %></p><% end %>

Upvotes: 1

Related Questions