So I have code in my application that appends to a has_many relation with the "<<" operator like so:
class BlogPost < ActiveRecord::Base
has_many :comments
def add_comment(content)
@new_comment = Comment.create(content)
self.comments << @new_comment
end
end
And it seems to work. I never really questioned it or wondered when it calls "save" (I guess I never had a strong understanding of when to call "save" to begin with).
However, it seems that the after_save
hook on comments doesn't get activated in my add_comment
function, which prompts me to ask:
How does the <<
operator work in activerecord and where can I read more about it?
Thanks
When you use the shovel
operator (<<
), Rails automatically saves the associated object. So, when you do this:
self.comments << @new_comment
@new_comment
is added to the comments
collection and instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record.
From this documentation
collection<<(object, …) Adds one or more objects to the collection by creating associations in the join table (collection.push and collection.concat are aliases to this method). Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With