Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Shovel (<<) Operator

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

like image 921
cozos Avatar asked Oct 05 '15 04:10

cozos


Video Answer


1 Answers

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.

like image 134
K M Rakibul Islam Avatar answered Sep 18 '22 16:09

K M Rakibul Islam