0

In my rails model I need to call after_commit callback if and only if one of the table attributes is changed from one value to other.
This is working fine with after_update callback but I am invoking some additional tasks in the background and after_commit is the perfect one for this. Any suggestions?

Sample code

    after_commit :call_cli, :if=> :change

    def change  
      if self.status_changed?  
        filename = '/location/res.log'              
        File.open(filename, File::WRONLY) do |file|
          file.write self.status_change_was+"\n"
        end
      end
    end
ejo
  • 446
  • 1
  • 9
  • 23
  • **after_commit** is executing perfectly. But my requirement is such that it should run iff the table attribute changes. Let me give more details. – ejo Jun 06 '13 at 04:04
  • **after_commit** is working with out the condition since the self object is destroyed. I am struggling here because I can call CLI if the attribute value is changed. Could you please help me with some sample code. – ejo Jun 06 '13 at 04:58
  • I found [this question](http://stackoverflow.com/questions/7128073/after-commit-for-an-attribute) about conditional `after_commit`, in case you want to check out some other options. – James Chevalier Jul 13 '13 at 16:33

2 Answers2

1

There's actually a previous changes method, which I would recommend: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

Peter Ehrlich
  • 6,969
  • 4
  • 49
  • 65
0

Got it. Called another callback before_update and self.status_changed? value is stored in a flag as @flag = self.status_changed?
Thanks to this article - http://axonflux.com/offlining-denormalized-tasks-gotchas-with-off.
Also cheers to Dave Newton for the kind help.

ejo
  • 446
  • 1
  • 9
  • 23