[英]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.