Rails ActiveRecord 铲 (<<) 运算符

Rails ActiveRecord Shovel (<<) Operator

所以我的应用程序中有代码附加到与“<<”运算符的 has_many 关系,如下所示:

class BlogPost < ActiveRecord::Base    
    has_many :comments

    def add_comment(content)
        @new_comment = Comment.create(content)
        self.comments << @new_comment
    end
end

而且它似乎有效。我从来没有真正质疑过它或想知道它何时调用 "save"(我想我从来没有深刻理解何时开始调用 "save")。

但是,我的 add_comment 功能似乎没有激活评论的 after_save 挂钩,这促使我问:

<< 运算符如何在 activerecord 中工作?我在哪里可以阅读更多相关信息?

谢谢

当您使用 shovel 运算符 (<<) 时,Rails 会自动保存关联的对象。所以,当你这样做时:

self.comments << @new_comment

@new_comment 被添加到 comments 集合并立即触发更新 SQL 而无需等待对父对象的保存或更新调用,除非父对象是新记录.

来自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.

集合<<(对象,...)

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) or by setting their foreign keys to the collection’s primary key. 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.

示例:

class Group < ActiveRecord::Base
  has_many   :users
  has_many   :avatars, through: :users
end

class User < ActiveRecord::Base
  belongs_to :group
  has_one    :avatar
end

class Avatar < ActiveRecord::Base
  belongs_to :user
end

@group.avatars << Avatar.new   # this would work if User belonged_to Avatar rather than the other way around