locoboy
locoboy

Reputation: 38940

Passing flash hash from one controller to another controller

I have a create method in one controller and at the end of this controller I want redirect_to another controller/view. How will I be able to display a flash[:notice] after the first controller is done and the next redirect_to view is rendered?

Here's the code in the first controller:

if @list.save
        redirect_to root_path, :notice => "Created!"

I also noticed that it doesn't work here either:

if @list.save
    redirect_to root_path, :alert => "Created!"

Here's the routes file:

root :to => 'sessions#new'

Upvotes: 1

Views: 1409

Answers (3)

Baruch
Baruch

Reputation: 1133

What version of Rails are you on? The syntax you are using is a relatively new feature. Try doing it the long way:

flash[:notice] = 'Created'
redirect_to root_path

Upvotes: 0

Ola Tuvesson
Ola Tuvesson

Reputation: 5210

To persist a flash message over an additional request you can use flash.keep - from the flash section on Rails Guides:

Let's say this action corresponds to root_url, but you want all requests here to be redirected to UsersController#index. If an action sets the flash and redirects here, the values would normally be lost when another redirect happens, but you can use 'keep' to make it persist for another request.

Clarification: This solution only applies if you're losing the flash due to a double redirect.

Upvotes: 4

maček
maček

Reputation: 77778

Have you tried this?

redirect_to(whatever_path, :notice=>"hello world")

Also, you can use :error

redirect_to(whatever_path, :error=>"hello error")

Upvotes: 0

Related Questions