2012-11-30 20 views
0

嘗試從保存的對象獲取以前的值。想想這個場景的:如何在保存時獲取更改的值

 
@object = {:name => 'Dan', :occupation => 'student'} 
@object[:occupation] = 'Full time employee' 
@object.value_was[:occupation] # => 'student' 

我希望這是足夠的理解,有沒有方法value_was。更多我想在模型對象上做同樣的事情:

 
@student = Student.find(1) 
@student.occupation = 'Full time employee' 
@student.save 
@student.value_was(:occupation) # => 'student' 

任何幫助將不勝感激。

那將是很有益

回答

5

包括加載ActiveModel爲「dirty field marking」的支持,從而保留了之前和之後的狀態更改的字段。

您可以使用@student.occupation_was獲取之前的值occupation@student.occupation_changed?以確定值是否已更改。

這隻在保存之前起作用,因爲保存會重置值的更改狀態。但是,如果您需要在記錄保存後使用它,則可以在before_save回調中捕獲此數據。例如,您可以通過在before_save中複製#changed_attributes來保留所有更改,然後查詢它們。

+0

很好的答案!你也知道如何得到改變的對象,那真是太棒了!例如新對象:'@student#=> {:name =>'Dan',:職業=>'全職員工',並通過調用我在髒字段中找不到的方法get - ' @ student.was#=> {:name =>'Dan',:職業=>'學生'}' –

+1

你會想要'@ student.previous_changes',它應該返回一個由保存更改的列表。 –

+0

返回空hash {} –

相關問題