Prev | Current Page 279 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


At this point, we have a command that will let us be able to tell when columns were overwritten
but doesn??™t let us keep a record of all the changes that have been made along the way.
We need to tinker with ActiveRecord::Base#save so we can record the audits the same time
the record gets saved. We can add the following code to the self.included function inside the
InstanceMethods module, which will wrap the save function:
def save_with_auditing(validations = true)
if save_without_auditing(validations)
@previous_attribute_values.each do |column, values|
Audit.create(:model => self, :column => column, :record_id => self.id,
:changed_from => values[:old], :changed_to => values[:new])
end
@previous_attribute_values = {}
end
end
alias_method :save_without_auditing, :save
alias_method :save, :save_with_auditing
With this code in place, we will have a number of Audit records created every time we
save a record: one for each column that we are watching and that we changed. For reference,
here is the migration I am using for the Audit class:
create_table :audits do |t|
t.


Pages:
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291