jlstr
jlstr

Reputation: 3056

Why is content_tag helper printing the "flash" contents in the browser?

To explain further, I have the following code in my Rails app Layout:

<!-- Stuff omitted -->
<% unless flash.empty? %>
  <%= flash.each do |name, msg| %>
    <%= content_tag :div, msg, :id => "flash_#{name}" %>
  <% end %>
<% end %>
<%= yield %>

And for the controller:

#stuff omitted
def create
  user = User.authenticate(params[:email], params[:password])
  if user
    session[:user_id] = user.id
    redirect_to root_url, :notice => "Logged in!"
  else
    flash.now.alert = "Invalid email or password"
    render :new
  end
end

Ok, so, If I happen to fail the authentication, this is what I'm seeing in the browser:

content_tag error?

Can you guys tell me why is the hash({:alert => "Invalid email or password"}) appearing under the message? I'm really clueless about what is wrong,

(BTW, This is taken from Rails Casts #250)

Upvotes: 1

Views: 591

Answers (3)

Th&#224;nh Vương
Th&#224;nh Vương

Reputation: 1

You can try the following:

  • in application.html.erb you can write:

    <% unless flash.empty? %>
      <% flash.each do |name, msg| %>
        <%= content_tag :div, msg, class: "alert alert-#{name}" %>
      <% end %>
    <% end %>
    <%= yield %>
    
  • in controller you can write:

    flash[:danger] = "Invalid email or password"

Upvotes: 0

BitOfUniverse
BitOfUniverse

Reputation: 6021

Just remove the equal sign from the start of the loop:

<!-- Stuff omitted -->
<% unless flash.empty? %>
  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, :id => "flash_#{name}" %>
  <% end %>
<% end %>
<%= yield %>

Because it tells ERB to print entire flash variable.

Upvotes: 4

WattsInABox
WattsInABox

Reputation: 4636

It looks like message ends up being a hash. Try setting the flash message like this:

flash[:alert] = "Invalid email or password"

Upvotes: 1

Related Questions