Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, in the model is there a way to provide a dif since the last update?

given a model like:

class SentenceItem < ActiveRecord::Base

  after_update :send_changes

  def send_changes
     #### Is it possible to do a diff here with dirty/changed? Showing what's changed since the last save?
  end

end

And that the sentence modle has a text field.

Is it possible to do a diff here with dirty/changed? Showing what's changed since the last save?

Thanks

like image 241
TheExit Avatar asked Jul 01 '11 16:07

TheExit


1 Answers

Yes, there is a way. From the ActiveModel::Dirty documentation:

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']

Which attributes have changed?

person.name = 'Bob'
person.changed        # => ['name']
person.changes        # => { 'name' => ['Bill', 'Bob'] }
like image 195
Mark Thomas Avatar answered Oct 16 '22 20:10

Mark Thomas