2011-02-10 38 views
3

我在我的模型下面的方法調用存取方法從模型對象內的Rails

def reset_review_status 
    needs_review = true 
    save 
end 

有型號叫做needs_review的屬性,但是當我調試它,它保存爲一個新變量。如果我做self.needs_review=true,它工作正常。我沒有attr_accessible子句,雖然我有一個accept_nested_attributes_for。

有關爲什麼會發生這種情況的任何想法?

回答

4

當你定義在ActiveRecord的一個屬性,可用以下方法

# gets the value for needs_review 
def needs_review 
end 

# sets the value for needs_review 
def needs_review=(value) 
end 

可以調用使用

needs_review = "hello" 

二傳手,但是這是你設置一個變量一樣。當你在一個方法中調用語句時,Ruby會賦予變量賦值更高的優先級,因此將創建一個具有該名稱的變量。

def one 
# variable needs_review created with value foo 
needs_review = "foo" 
needs_review 
end 

one 
# => returns the value of the variable 

def two 
needs_review 
end 

two 
# => returns the value of the method needs_review 
# because no variable needs_review exists in the context 
# of the method 

作爲一個經驗法則:當你想調用一個方法

  • 內設置方法時具有相同名稱的局部變量的背景下,存在有選擇地使用self.method_name

    1. 始終使用self.method_name =