Wednesday, April 29, 2009

ActiveRecord::Dirty

Another powerful feature of ActiveRecord is dirty objects. This module tracks unsaved attribute changes. This feature is available probably since March, 2008. See examples below:

A newly instantiated object is unchanged:

person = Person.find_by_name('uncle bob')
person.changed? # => false

Change the name:

person.name = 'Bob'
person.changed? # => true
person.name_changed? # => true
person.name_was # => 'uncle bob'
person.name_change # => ['uncle bob', 'Bob']
person.name = 'Bill'
person.name_change # => ['uncle bob', 'Bill']

Save the changes:

person.save
person.changed? # => false
person.name_changed? # => false

Assigning the same value leaves the attribute unchanged:

person.name = 'Bill'
person.name_changed? # => false
person.name_change # => nil

Which attributes have changed?

person.name = 'bob'
person.changed # => ['name']
person.changes # => { 'name' => ['Bill', 'bob'] }

Before modifying an attribute in-place:

person.name_will_change!
person.name << 'by'
person.name_change # => ['uncle bob', 'uncle bobby']

2 comments:

Nick Carter said...

And remember, you also have one of these "dirty methods" available in JazzRecord: record.isChanged() returns a bool if any properties the record have changed since it was last saved. I've thought about implementing more of these methods if there was interest...

chamnap said...

Sure. I saw it in your code. Anyway, it is cool enough for my project.

Subscribe in a Reader