Rails dirty objects

February 25, 2011

Rails is truly the work of visionary people, leveraging the all powerful Ruby language they came up with something that is really nice to use and that produce very powerful results, digging into the API i find a very powerful feature called Rails dirty objects, i havent heard about that until recently, when i learned that you could so stuff like this:

  person = Person.find_by_name('uncle bob')
  person.changed?       # => false
  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']
  person.save
  person.changed?       # => false
  person.name_changed?  # => false
  person.name = 'bob'
  person.changed        # => ['name']
  person.changes        # => { 'name' => ['Bill', 'bob'] }

neat isnt it?

Comments

comments powered by Disqus