2010-01-27 27 views
3

如果您編寫my_obj.attr,主要在導軌中,它在數據庫中查找attr並報告回來。你如何創建一個自定義def attr方法,內部查詢attr數據庫,修改它並返回?換句話說,什麼是缺失的環節在這裏:導軌中的定製attr_reader

# Within a model. Basic attr_reader method, will later modify the body. 
def attr 
    get_from_database :attr # <-- how do I get the value of attr from the db? 
end 

回答

3

類似的東西:

def attr 
    value = read_attribute :attr 
    value = modify(value) 
    write_attribute :attr, value 
    save 
    value 
end 
1

,如果你想每次獲取屬性時保存回修改的值到數據庫中微子的方法是好的。不建議這樣做,因爲每次嘗試讀取屬性時即使它沒有更改也會執行額外的數據庫查詢。

如果您只是想修改的屬性(如要用大寫字母例如),你只需做到以下幾點:

def attr 
    return read_attribute(:attr).capitalize #(or whatever method you wish to apply to the value) 
end 
+0

這個問題本身實際上是什麼的意思有點不清楚你的時候做「修改「的價值。如果你不想存儲它,那麼顯然沒有必要保存模型:) – 2010-01-27 10:38:17

+0

def attr self [:attr] .capitalize end 也可以工作 – psyho 2010-01-27 15:24:31