[英]Track changes to model and save results to another model
我正在使用Rails 3.2應用程序。 我希望當管理員用戶通過CRUD更改名為Candidate的模型中的某些字段時,將其保存到Update模型中(這是通過標准Rails腳手架方法中的update_attributes調用發生的)。
我在候選模型中有代碼,該模型跟蹤before_save過濾器中的更改:
before_save :check_changed
def check_changed
period_contributions_changed?
end
這位於候選人模型文件候選人.rb中。
我想要在period_contributions和其他指定字段中更改值,以觸發另一個記錄Update的創建。
更新將包含候選ID,已更改字段的名稱,先前值和新值。
似乎需要模型代碼在Update控制器上調用方法,這似乎是一種不好的做法。 有最佳做法嗎?
ActiveRecord
提供了一些您可以利用的方法
changed?
->告訴您ID,對象已更改 changed
->給出了已更改的屬性數組 changed_attributes
>為您提供一個哈希,其鍵為已更改的屬性,值為舊值
before_save :log_changed def log_changed if self.changed? self.changed.each do |attr| Update.create(:candidate_id => self.id, :field => attr, :new_value => self.attributes[attr], :old_value => self.changed_attributes[attr]) end end end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.