[英]Rails application variable life cycle question
假设我在应用程序中有一个全局变量用户。
# GET /users.xml
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end
这是否意味着每个请求都会创建一个新的@user? 如果每个请求都创建了一个对象,则何时将其销毁? 同样,如果vistorA转到网站,则创建一个@userA,而vistorB转到网站@userB。 vistorA是否有机会获得vistorB的对象(@userB)? 另外,对象何时释放? 谢谢。
****更新:@users不是全局变量,它是一个实例变量。 因此,有一个后续问题。 服务器如何知道哪个@user属于哪个请求? 谢谢。
@users
不是全局变量,而是实例变量 。 创建了控制器的新实例来处理每个请求,因此访问者A和访问者B的@users
是独立的。
1] @users不是全局变量,它是实例变量。它的scopre仅保留到该方法。
def index
@some_variable= "Hello"
other_method
redirect_to :action=>'redirect_method'
end
def other_method
#here you get @some_variable ="Hello" as you called this method in index where variable is initialise
end
def redirect_method
#here you get @some_variable as you not called this method in index but redirected to this method
end
2]对于每个用户,@ users会有所不同,因为每个请求都由服务器独立处理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.