开发者

Ruby on Rails: How to have ActiveRecord callback load a shared variable between callbacks

开发者 https://www.devze.com 2023-04-09 10:27 出处:网络
I have a couple of before_save and after_save callbacks that need to share an instance of an object between each other in a Ruby on Rails project. I thought that adding an additional method called loa

I have a couple of before_save and after_save callbacks that need to share an instance of an object between each other in a Ruby on Rails project. I thought that adding an additional method called load_object where I load the object into an instance variable would do the trick. This worked fine for the before_save validations, but the object di开发者_C百科dn't persist to the after_save chain of methods. Is there anyway to make sure it's around for both sets while keeping my code DRY?


that's strange, the callbacks run on the same instance, and any instance variable should still be available (though not persisted). but you can always use an around_save callback

around_save :do_something

def do_something
  #beforesave things
  yield
  #aftersave things
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号