127

I'm trying to do a redirect while setting the flash[:error] value. (Rails 3.0.10)

In my view I have

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

If I do a redirect_to show_path, :notice => "ok" it works fine, but if I do redirect_to show_path, :error => "error" it doesn't show up.

what could I be missing?

Daniel
  • 1,515
  • 3
  • 10
  • 13

4 Answers4

249

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!" }
Bijan
  • 25,559
  • 8
  • 79
  • 71
Tarnschaf
  • 3,955
  • 1
  • 26
  • 36
  • 4
    For clarity: `redirect_to(show_path, {:flash => { :error => "Insufficient rights!" }})`. This format is needed if you want to create show_path with url options. – spyle Apr 16 '13 at 20:00
  • 2
    That worked for me too, I just wonder what the thought was behind only notice/alert being in the flash hash – jbnunn Aug 16 '13 at 22:31
  • 2
    Worked in Rails 5 – Richard Peck Oct 28 '16 at 15:09
  • 1
    You can move away from ruby 1.9 format to: `redirect_to(show_path, flash: { error: "Insufficient rights!" })` – mmsilviu Oct 24 '18 at 14:42
17

If you are having problem to keep the flash after redirecting to another path, then use this.

flash.keep

in your method, before redirecting.

halfdan
  • 33,545
  • 8
  • 78
  • 87
Ramiz Raja
  • 5,942
  • 3
  • 27
  • 39
0

controller.rb

flash[:sucess] =  "Your sucess message"
redirect_to action: :index

layout.html

<% if flash[:sucess] %>
    <div class="alert alert-solid-success alert-bold" role="alert">
        <div class="alert-text"><%= sanitize(flash[:sucess]) %></div>
    </div>
<% end %>
sparkle
  • 7,530
  • 22
  • 69
  • 131
-1

To truly follow the PRG pattern, I wonder if this project works well

https://github.com/tommeier/rails-prg

I can't stand apps not following PRG as a user.....I have been 6 pages after a POST and hit the back button to get back to 10 pages ago get blocked by "do you want to repost this crap"....no, of course not. I just want to get back to a page I had seen before.

non-PRG apps are very very annoying to users.

Dean Hiller
  • 19,235
  • 25
  • 129
  • 212