¿Por qué content_tag helper imprime el contenido "flash" en el navegador?

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)

preguntado el 08 de noviembre de 11 a las 14:11

3 Respuestas

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.

respondido 08 nov., 11:18

Yes, I can't believe I didn't see this one. I'm sorry, this is so embarrassing. Anyways, Thank you very much for your time ! - jlstr

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

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

respondido 08 nov., 11:18

Sorry, the result is the same. I just don't get it, the hash is being printed outside the div created by content_tag. I don't know why. - jlstr

Do you have an errant debug statement somewhere? Like a to_yaml call? a <%= debug flash %> for a <%= y flash %> ? - WattsInABox

negative sir, I don't. The app is very small(given it just follows a rails cast) - jlstr

I've got it! this is so embarrasing.. the problem is the equals in this expression: <%= flash.each do |name, msg| %> - jlstr

Puedes probar lo siguiente:

  • in application.html.erb puedes escribir:

    <% 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"

Respondido el 07 de junio de 17 a las 16:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.