0

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?

10
  • I dont see why the value should be reset if all you are doing is printing from the second method. Commented 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? Commented 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? Commented 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? Commented Aug 19, 2011 at 3:40
  • 1
    yes 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. Commented Aug 19, 2011 at 3:45

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Gotcha. That last line is essential. I needed reminded of that. What is the lifetime of a session variable?
@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).
0

Yes, you can use an instance variable to achieve that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.