code_junkie

Using the after_save callback to modify the same object without triggering the callback again (recursion)

Nov 11th, 2011
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. def your_after_save_func
  2. YourModel.without_callbacks(:your_after_save_func) do
  3. Your updates/changes
  4. end
  5. end
  6.  
  7. send(name.to_s + '=', value)
  8.  
  9. def before_save
  10. @attempted_save_level ||= 0
  11. @attempted_save_level += 1
  12. end
  13.  
  14. def after_save
  15. if (@attempted_save_level == 1)
  16. #fill in logic here
  17.  
  18. save #fires before_save, incrementing save_level to 2, then after_save, which returns without taking action
  19.  
  20. #fill in logic here
  21.  
  22. end
  23. @attempted_save_level -= 1 # reset the "prevent infinite recursion" flag
  24. end
  25.  
  26. Class Foo << ActiveRecord::Base
  27. after_save :init_bar_attr, :if => "bar_attr.nil?" # just make sure this is false after the callback runs
  28.  
  29. def init_bar_attr
  30. self.bar_attr = "my id is: #{self.id}"
  31.  
  32. # careful now, let's save only if we're sure the triggering condition will fail
  33. self.save if bar_attr
  34. end
Add Comment
Please, Sign In to add comment