1

I am just looking to seek some clarification to accessing Instance variables within its class (apologies if this is really basic).

My example is that I have a recipe controller and within it I have many actions but in paticular I have an INDEX and a SHOW action

def index
@q = Recipe.search(params[:q])
@q.build_condition
end

@q searches my Recipe model based on the params passed through my search form

i want to show the results on a different page to start (will look at AJAX option later), so in my SHOW action could I do this

 def show
 @searchresults = @q.result(:distinct => true)
 end

I think this is valid but if not I am going wrong somewhere. Can anyone advise or offer some constructive advice?

Thank you

2 Answers 2

3

your object or class should have the following methods:

  • @foo.instance_variables - this will list the names of the instance variables for @foo
  • @foo.instance_variable_get - this will get the value of an instance variable for @foo
    • ex: @foo.instance_variable_get("@bar") - this would get the value of the instance variable named @bar for @foo
Sign up to request clarification or add additional context in comments.

Comments

1

No you can't use instance variable like this because they both have different action and will get called for the different request.

However following will work

def index
  @q = Recipe.search(params[:q])
  @q.build_condition
  show
end

def show
  #Following line will work as we are calling this method in index 
  #and so we can use instance variable of index method in the show methos 
  @searchresults = @q.result(:distinct => true)
end

1 Comment

thank you for your answer, so if for example i placed search results instance variable within a results action i would just call results in my index..think you have cleared things up for me here

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.