Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after_commit for an attribute

I am using an after_commit in my application.

I would like it to trigger only when a particular field is updated in my model. Anyone know how to do that?

like image 230
alik Avatar asked Aug 19 '11 22:08

alik


3 Answers

Old question, but this is one method that I've found that might work with the after_commit callback (working off paukul's answer). At least, the values both persist post-commit in IRB.

after_commit :callback, 
  if: proc { |record| 
    record.previous_changes.key?(:attribute) &&
      record.previous_changes[:attribute].first != record.previous_changes[:attribute].last
  }
like image 120
d_ethier Avatar answered Nov 11 '22 22:11

d_ethier


Answering this old question because it still pops up in search results

you can use the previous_changes method which returnes a hash of the format:

{ "changed_attribute" => ["old value", "new value"] }

it's what changes was until the record gets actually saved (from active_record/attribute_methods/dirty.rb):

  def save(*) #:nodoc:
    if status = super
      @previously_changed = changes
      @changed_attributes.clear
      # .... whatever goes here

so in your case you can check for previous_changes.key? "your_attribute" or something like that

like image 23
Pascal Avatar answered Nov 11 '22 22:11

Pascal


Old question but still pops up in search results.

As of Rails 5 attribute_changed? was deprecated. Using saved_change_to_attribute? instead of attribute_changed? is recommended.

like image 8
sledge_909 Avatar answered Nov 11 '22 22:11

sledge_909