From my point of view, this is not a mistake. Everything works as expected. You can create a complex graph of objects before saving this graph. At this point in the creation, you can add objects to the association. This is the moment you want to run this callback because it says after_add, not after_save.
For instance:
@post.tags.build name: "ruby"
@post.tags.build name: "rails"
@post.save!
Perhaps with a callback before_addthis makes 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"
@post.save!
You can read a little about this callback in The Rails 4 Way.
. , after_save.
2 : .
. .