I have a controller. In the controller I have two methods. I would like a variable whose value is set in method 1 to be accessible in method 2. Could I use an instance variable to achieve this?
-
I dont see why the value should be reset if all you are doing is printing from the second method.DaMainBoss– DaMainBoss2011-08-19 03:30:08 +00:00Commented Aug 19, 2011 at 3:30
-
So normally I would have no issues accessing an instance variable set in one method in another method of the same class?Drew– Drew2011-08-19 03:33:03 +00:00Commented Aug 19, 2011 at 3:33
-
If so, would there be a setting in the application controller that could be causing me to lose the value?Drew– Drew2011-08-19 03:33:54 +00:00Commented Aug 19, 2011 at 3:33
-
are you accessing method 1 and method 2 from the same request? same thread? Or are you setting the instance variable on 1 page, and trying to read it from another?Doon– Doon2011-08-19 03:40:31 +00:00Commented Aug 19, 2011 at 3:40
-
1yes you will need to throw it in the session. Since if you set it in the instance, when you come back to that controller it is a new request. throw it in the session and you can pull it out on another page.Doon– Doon2011-08-19 03:45:55 +00:00Commented Aug 19, 2011 at 3:45
|
Show 5 more comments
2 Answers
Yes, you could use an instance variable for this as long as everything is happening in a single request.
So something like this:
class PancakesController < ApplicationController
def where_is
@house = Pancake.find(params[:id])
render :json => mangle, :status => :ok
end
private
def mangle
@house
end
end
will work as expected. However, this sort of thing:
class PancakesController < ApplicationController
def where_is
@house = Pancake.find(params[:id])
#...
end
def mangle
if(@house)
#...
end
#...
end
end
won't work if where_is and mangle are called in difference requests.
Remember that the lifetime of a controller instance is a single request.
2 Comments
Drew
Gotcha. That last line is essential. I needed reminded of that. What is the lifetime of a session variable?
mu is too short
@Drew: Session values will last until the session expires or the person logs out; you can use the session to pass things between controller calls but you usually don't want anything too big in the session and you still have to be prepared for it to disappear (but it should be okay for short term purposes).