Ruben
Ruben

Reputation: 1093

Flash[:error] is not shown when user is redirected

I am implementing in Ruby on Rails, and when a user filled in something wrong, or something wrong is happened, the user has to go back to the previous page, and with a correct error message. I tried to do this with:

redirect_to 'javascript:history.go(-1)', flash.now[:error] =>"Something went wrong"

Now, this goes back to the previous page, but this without the flash error? Does someone know how to fix this?

Thanks in advance!

EDIT: I tried :

 redirect_to 'match', :notice => 'Something went wrong'

Match is the previous page, but now I get an error from my browser:

No data received
Unable to load the webpage because the server sent no data.

Upvotes: 0

Views: 673

Answers (3)

Coren
Coren

Reputation: 5637

You can't mix Javascript and Ruby this way. Your Javascript call does not make any side-server action, so your ruby code is never executed.

default error handling of Ruby on Rails is quite convenient and if you can, it's better to use it.

If you really cannot use it, you'll have to choose between Ruby and Javascript for this matter. The recommended way is the Ruby way :

redirect_to user_path(@user), :notice =>"The user was successfully created"

see this post of Ryan for more detail. I am not sure if this is possible in Javascript, because you'll have to pass error information to the previous page without reloading it.

Upvotes: 3

Matt
Matt

Reputation: 1143

flash.now triggers the flash in the same rendering sequence. After a redirect you are on a newly rendered page and therefor your shouldn't use flash.now but something like

redirect_to :back, error: 'Something went wrong'

Upvotes: 1

Hauleth
Hauleth

Reputation: 23556

Use:

redirect_to :back, :flash => {:error => "Error"}

Upvotes: 2

Related Questions