kimkunjj
kimkunjj

Reputation: 1006

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?

Upvotes: 10

Views: 17344

Answers (3)

Justin D.
Justin D.

Reputation: 4976

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!" }

Upvotes: 5

Sinstein
Sinstein

Reputation: 909

This is how I display alerts and notices in my controller

redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been uploaded."

Use flash[:error] or flash[:notice] when you are rendering over the current page and not redirecting like here:

if params[:attachment].nil?
      flash.now[:alert] = "No file found!"
      render "new"
else

Upvotes: 0

Astockwell
Astockwell

Reputation: 1536

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.

Upvotes: 5

Related Questions