开发者

Instance variable in rails - apart from views where can we use it and for how long is it available

I have created a instance variable in rails project, which gets its value from a url parameter like example.com/value. This variable is created in new action, now can it also be used in create action, of the same model.

The value is a id of another model altogether and both the models are associated, I need to create the instance variable in former model.

I need to know, for how long the instance variable is available, and can be use the instance variable of开发者_如何学JAVA one model in another model.

Clarification with real example

Supposingly there are two models, one is User model and other is Referral model. The root is root :to => 'users#new. Now the user will coming here via example.com/value, where value is the id for Referral model. Now using this value I have to increment two fields: One is visits, which shows how many visits did that particular url bring. Other is signup, which will increment if there is a signup using that value.

I have passed this value via routes in users#new, which I use to increment the visits column of Referral model. Now if the users signup, the users#create would be executed, and I want to be able to use the value in the create action as well, to increment the signup column in Referral model.

As of now, I understand that the instance variable I created in new action to store the value cannot be used in create action. Now how can I achieve this.


In general instance variables only last as long as the user's HTTP request, so they can not be created in one action and used in another.

You could try storing the variable in the session, a hidden input field on the HTML form generated by the new action, or in the urls of links generated by the new action.

I don't know exactly what you are doing, but from the names of your two actions it sounds like there is probably an HTML form involved, so I think the best thing is to use a hidden input, something like this:

<input type="hidden" name="model_id" value="<%= @model_id %>" />


Instance variables only last for that call and in the class they are defined, with the exception of the views. If you have a controller with two methods where one method is your route and another is used internally, then it will be available to both, it is also available to your views.

e.g.

test_controller.rb

def index
  something_else
  p @variable #outputs "foo" in the terminal
end

def something_else
  @variable = "foo"
end

However it would not be available between create and new as these would be called in different requests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜