Using ActiveRecord, is there a way to get the old values of a record during after_update

后端 未结 10 1046
耶瑟儿~
耶瑟儿~ 2021-01-30 08:20

Setup using a simple example: I\'ve got 1 table (Totals) that holds the sum of the amount column of each record in a second table (

相关标签:
10条回答
  • 2021-01-30 08:49

    Appending "_was" to your attribute will give you the previous value before saving the data.

    These methods are called dirty methods methods.

    Cheers!

    0 讨论(0)
  • 2021-01-30 08:52

    Some other folks are mentioning wrapping all this in a transaction, but I think that's done for you; you just need to trigger the rollback by raising an exception for errors in the after_* callbacks.

    See http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

    The entire callback chain of a save, save!, or destroy call runs within a transaction. That includes after_* hooks. If everything goes fine a COMMIT is executed once the chain has been completed.

    If a before_* callback cancels the action a ROLLBACK is issued. You can also trigger a ROLLBACK raising an exception in any of the callbacks, including after_* hooks. Note, however, that in that case the client needs to be aware of it because an ordinary save will raise such exception instead of quietly returning false.

    0 讨论(0)
  • 2021-01-30 08:53

    ActiveRecord::Dirty is a module that's built into ActiveRecord for tracking attribute changes. So you can use thing.amount_was to get the old value.

    0 讨论(0)
  • 2021-01-30 08:54

    To get all changed fields, with their old and new values respectively:

    person = Person.create!(:name => 'Bill')
    person.name = 'Bob'
    person.save
    person.changes        # => {"name" => ["Bill", "Bob"]}
    
    0 讨论(0)
提交回复
热议问题