[英]Lifecycle of Instance variables in Ruby on Rails
I am not quite clear on the life cycle of instance variables in Ruby on Rails. 对于Ruby on Rails中实例变量的生命周期,我还不太清楚。
I have an instance variable @work_days
(into which I fetch and load the list of all working days in a month. The month is selected by the user from a date_select
in the UI). 我有一个实例变量
@work_days
(在其中获取并加载一个月中所有工作日的列表。用户从用户界面中的date_select
中选择月份)。
Now I have a Generate Report
button which generates an excel report by calling a show
method in the controller 现在,我有一个“
Generate Report
按钮,可通过在控制器中调用show
方法来生成excel报告
Every time the user clicks the Generate Report
button (and show
method gets called), the value of @work_days
seems to be nil
and I have to initialize it every time. 每次用户单击“
Generate Report
按钮(并且调用show
方法)时, @work_days
的值似乎为nil
,我每次都必须对其进行初始化。
Is there a way to avoid this? 有办法避免这种情况吗? Why does the value of instance variable become
nil
every time the controller's method show
is called? 为什么每次调用控制器的方法
show
时实例变量的值都变为nil
?
Rails controller is instantiated per request. 每个请求都会实例化Rails控制器。 It means that every time you receive a request all instance variables are
nil
and you need to initialize them. 这意味着,每次收到请求时,所有实例变量均为
nil
,则需要对其进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.