Rails 为数组中的每条记录添加关联(has_many 到)

Rails add association (has_many through) for each record in array

我有一个 task 模型,它有很多 groups_belonging_to 通过另一个 table (task_group_relationships):

has_many :task_group_relationships, class_name: "TaskGroupRelationship",
                          foreign_key: "task_id",
                          dependent: :destroy
has_many :groups_belonging_to, through: :task_group_relationships, source: :task_group

在为任务数组中的每条记录添加关联时,我知道我可以这样做:

tasks.each do |task|
    task.groups_belonging_to << task_group
end

但是有什么方法可以一次添加所有关联以节省对数据库的多次调用?

我刚刚用谷歌搜索并找到 this post,这很有帮助。

因此,用事务包装您的插入内容应该会有所帮助。像这样:

ActiveRecord::Base.transaction do
  tasks.each do |task|
      task.groups_belonging_to << task_group
  end
end