Ruby on rails Rails 5:在“has_many through”关系中添加/编辑多条记录

Ruby on rails Rails 5:在“has_many through”关系中添加/编辑多条记录,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有很多经典的关系,我需要能够添加多个公司到特定的用户。模型如下所示: class Company < ApplicationRecord has_many :accounts, dependent: :destroy has_many :users, through: :accounts end class Account < ApplicationRecord belongs_to :company, inverse_of: :accounts belongs_

我有很多经典的关系,我需要能够添加多个公司到特定的用户。模型如下所示:

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
如何在一次查询中为用户添加、编辑、删除多个帐户?我需要将多个公司附加到用户,然后根据需要编辑/删除

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

[4] pry(main)> user.accounts.create(company_id: [1,2])
   (0.4ms)  BEGIN
  User Exists (1.3ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER($1) AND ("users"."id" != $2) LIMIT $3  [["email", "tester@gmaill.com"], ["id", 7], ["LIMIT", 1]]
   (0.6ms)  COMMIT
=> #<Account:0x00000005b2c640 id: nil, company_id: nil, user_id: 7, created_at: nil, updated_at: nil>
据我所知,我需要以某种方式创建阵列,然后使用它进行操作。我将非常感谢您的帮助。谢谢大家!

解决方案


如果有人需要的话,我解决问题的方式有点不同。我用过,它对我来说很好。

这里有一个关于gem的例子:


由于用户有许多帐户,所以可以接受用户模型中帐户的嵌套属性。现在,帐户属于公司和用户。因此,对于公司,您可以在字段_中为Account.@prasad.surase提供一个选择框,谢谢。是的,这可能是我能做的。现在我在想,我该如何在控制台中编写它才能看到它为用户添加了多个公司?gem可以使用。@maxple谢谢,我不知道。我预计每个用户最多有5家公司。不确定这是否是批量插入案例。有没有一些相对简单的查询可以做到这一点?事实上,与手工构建insert to SQL语句相比,bulk_insert相对简单,这是人们有时会做的事情。好吧,我可以试试这个。据我所知,这将有助于向用户添加公司。如何进行编辑,例如,删除ID=2的公司,并将ID=3的公司添加到ID=1的用户?bulk_insert gem是否也可以执行一些更新操作,或者我会执行其他操作?在单个查询中删除和创建的SQL要比我熟悉的复杂得多。rails中已经有了update_all和delete_all,但据我所知,插入操作没有类似的操作。是的,我很熟悉update_all-在我的一个模型中使用它,效果很好。我最初的想法是使用这种标记方法——但是到目前为止,我还没有在我的案例中使用它。
[4] pry(main)> user.accounts.create(company_id: [1,2])
   (0.4ms)  BEGIN
  User Exists (1.3ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER($1) AND ("users"."id" != $2) LIMIT $3  [["email", "tester@gmaill.com"], ["id", 7], ["LIMIT", 1]]
   (0.6ms)  COMMIT
=> #<Account:0x00000005b2c640 id: nil, company_id: nil, user_id: 7, created_at: nil, updated_at: nil>
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
)