我在我的rails 3.1.6應用程序中有一個自定義的存取器方法,它爲值賦給一個屬性,即使這個值不存在。my_attr屬性是一個序列化的哈希,它應該與給定的值合併,除非一個空值被指定,在這種情況下,它會將當前值設置爲空白值。 (有加檢查,以確保該值應該是什麼,但爲了簡便起見被刪除,因爲它們不是我的問題的一部分。)我的二傳手定義爲:Rails模型中自我的價值是什麼?爲什麼不提供明顯的實例方法?
def my_attr=(new_val)
cur_val = read_attribute(:my_attr) #store current value
#make sure we are working with a hash, and reset value if a blank value is given
write_attribute(:my_attr, {}) if (new_val.nil? || new_val.blank? || cur_val.blank?)
#merge value with new
if cur_val.blank?
write_attribute(:my_attr, new_val)
else
write_attribute(:my_attr,cur_val.deep_merge(new_val))
end
read_attribute(:my_attr)
end
此代碼的工作以及 - 是,但不是當我使用self.write_attribute()時。然後我得到了以下錯誤:
NoMethodError:
private method `write_attribute' called for #<MyModel:0x00000004f10528>
我的問題是這樣的:它似乎更符合邏輯有可用實例write_attribute,那麼爲什麼只對類和不的實例?在Ruby或Rails(或兩者)中,我的基本知識self中是否存在某些缺陷?