Rails 5:在“has_many through”关系中添加/编辑多个记录

时间:2017-04-04 15:46:52

标签: ruby-on-rails ruby activerecord

我有经典的var extract_company_name = function(email){ var temp = email.replace(/.*@/, '').split('.'); return temp[temp.length - 2]; } extract_company_name(email) 关系,我需要能够将多家公司添加到特定用户。模型看起来像这样:

has_many through

在控制台中我可以添加单个记录:

class Company < ApplicationRecord
  has_many :accounts, dependent: :destroy
  has_many :users, through: :accounts
end

class Account < ApplicationRecord
  belongs_to :company, inverse_of: :accounts
  belongs_to :user, inverse_of: :accounts
  accepts_nested_attributes_for :company, :user
end

class User < ApplicationRecord
  has_many :accounts, dependent: :destroy
  has_many :companies, through: :accounts
end

如何在一个查询中为用户添加,编辑,删除多个帐户?我需要将多个公司附加到用户,然后根据需要编辑/删除。

到目前为止,我试图实现数组部分from this tutorial,但不知何故它不起作用显然我在这里做错了什么:

[1] pry(main)> user=User.find(7)
[2] pry(main)> user.accounts.create(company_id: 1)

据我所知,我需要以某种方式创建数组然后使用它。我很感激这里的任何帮助。谢谢!

解决方案

如果有人需要,我的解决方法有点不同。我使用了checkboxes from this tutorial,对我来说效果很好。

1 个答案:

答案 0 :(得分:1)

以下是bulk_insert gem的示例:

company_ids = [1,2]
user_id = 1

Account.bulk_insert(
  values: company_ids.map do |company_id|
    {
      user_id: user_id,
      company_id: company_id,
      created_at: Time.now,
      updated_at: Time.now
    }
  end
)