Rails HABTM after_add callback fires before saving primary object

廉价感情. 提交于 2019-12-05 15:24:50

In my point of view it is not a bug. Every thing works as expected . You can create a complex graph of objects before you save this graph. During this creation phase, you can add objects to an association. This is the point in time where you want fire this callback, because it says after_add and not after_save.

For instance:

@post.tags.build name: "ruby" # <= now you add the objects
@post.tags.build name: "rails" # <= now you add the objects
@post.save! # <= now it is to late, for this callback, you added already multiple objects

Maybe with a before_add callback it makes more sense:

class Post
   has_many :tags, before_add: :check_state

   def check_state(_tag)
     if self.published?
        raise CantAddFurthorTags, "Can't add tags to a published Post"
     end
   end
end

@post = Post.new
@post.tags.build name: "ruby" 
@post.published = true
@post.tags.build name: "rails" # <= you wan't to fire the before_add callback now, to know that you can't add this new object 
@post.save! # <= and not here, where you can't determine which object caused the error

You can read a little bit about these callback within the book "The Rails 4 Way"

In your case you have to rethink your logic. Maybe you can use an after_savecallback. My 2 cents: You consider switching from callbacks to service object. Callbacks don't come without a cost. They are not always easy to debug and test.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!