Reputation: 15374
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
Upvotes: 1
Views: 2027
Reputation: 47472
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
Upvotes: 1
Reputation: 18572
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
@foo.instance_variable_get("@bar")
- this would get the value of the instance variable named @bar
for @foo
Upvotes: 3