barfurth
barfurth

Reputation: 661

Add to / modify request.env in a controller

How could I modify request.env in a controller? I want to do something like this:

request.env["newkey"] = content

And then in the next controller, that I redirect_to from the one that sets the env, I want to use request.env["newkey"] to access the content.

So how would I modify request.env?

Upvotes: 1

Views: 2120

Answers (1)

Prakash Murthy
Prakash Murthy

Reputation: 13077

request.env["newkey"] = content does work in adding the new key to the request.env object.

However, that doesn't help in what you are trying to accomplish because on redirecting, it is a new request, and the request.env object is recreated. The newkey set in the previous request is lost.

What you need to use is rails flash.

The flash provides a way to pass temporary primitive-types (String, Array, Hash) between actions. Anything you place in the flash will be exposed to the very next action and then cleared out.

Set the value in the first method as follows:

def <first_method>
  ...
  flash[:newkey] = params[:number]
  redirect_to ...
end

Then it can be accessed in the redirected_to method as follows:

 def <redirected_to_method>
   ...
   new_key_val = flash[:newkey]
   ...
 end

Upvotes: 2

Related Questions