Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails flash message not showing in redirect_to

In one controller I have

flash[:error] = "Message"
redirect_to :root

The :root is handled by another controller, the view has

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

But nothing is being shown. I inserted <%= debug controller.session %>, here's what I got

"flash"=>#<ActionDispatch::Flash::FlashHash:0x2e79208 @used=#<Set: {}>, @closed=false, @flashes={}, @now=nil>}

What did I do wrong?

like image 942
kimkunjj Avatar asked Apr 01 '12 12:04

kimkunjj


2 Answers

I know this is late, but I had the same problem in Rails 4. If you use the _url helper in the redirect_to, the flash message will come through:

def update_post
    respond_to do |format|
        if @post.update(post_params)
            format.html { redirect_to show_post_meta_url, notice: 'Post was successfully updated.' }
        else
            format.html { render action: 'edit_post' }
        end
    end
end

Hope this helps someone.

like image 159
Astockwell Avatar answered Nov 02 '22 23:11

Astockwell


Update (2019): This answer might not be up to date according to comments.

Check this question: Rails: redirect_to with :error, but flash[:error] empty .

As stated in the Rails API only :notice and :alert are by default applied as a flash hash value. If you need to set the :error value, you can do it like this:

redirect_to show_path, :flash => { :error => "Insufficient rights!" }
like image 20
Justin D. Avatar answered Nov 02 '22 21:11

Justin D.