I'm in a Rails 3.2 app. I want certain fields in a model called Candidate to be saved into an Update model when the admin user changes them via the CRUD (which happens with an update_attributes call in the standard Rails scaffold way).
I've got code in a Candidate model which tracks changes in a before_save filter:
before_save :check_changed
def check_changed
period_contributions_changed?
end
This is inside candidate.rb, the Candidate model file.
What I'd like is for a changed value in period_contributions and other specified fields to trigger the creation of another record, Update.
An Update would contain the candidate ID, the name of the field that changed, the previous value and the new value.
This seems like it would require the model code calling a method on the Update controller, which seems like bad practice. Is there a best practice for doing this?
ActiveRecord
provides some methods that you can make use of
changed?
-> tells you id the object is changedchanged
-> gives an array of attributes that changedchanged_attributes
-> gives you a hash with keys as the changed attributes and values as old value
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