2017-04-04 62 views
1

我有经典has_many through关系,我需要能够将多个公司添加到特定用户。模型是这样的:在一个查询用户Rails 5:在“has_many through”关系中添加/编辑多个记录

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

如何添加,编辑,删除多个帐户:

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,但不知何故,不作为显然我做错了的东西在这里工作:

[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", "[email protected]"], ["id", 7], ["LIMIT", 1]] 
    (0.6ms) COMMIT 
=> #<Account:0x00000005b2c640 id: nil, company_id: nil, user_id: 7, created_at: nil, updated_at: nil> 

据我了解,我需要以某种方式创建数组,然后与运营那。我很感谢这里的任何帮助。谢谢!

解决方案

如果有人需要,我解决我的问题有点不同。我使用checkboxes from this tutorial,它对我来说工作得很好。

+0

因为,用户有多个账户,就可以接受用户模型帐户嵌套的属性。现在,帐户属于公司和用户。因此,对于公司,您可以在fields_for帐户中提供一个选择框。 –

+0

@ prasad.surase谢谢。是的,这可能是我可以做的事情。现在我想,如何在控制台中编写它,看看它是否向用户添加了多个公司? – matiss

+0

可以使用[bulk_insert](https://github.com/jamis/bulk_insert)gem。 –

回答

1

下面是一个例子与bulk_insert宝石:

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 
) 
+0

好吧,我可以试试这个。据我了解,这将用于添加公司给用户。我可以如何编辑,例如,删除ID = 2的公司,并将ID = 3的公司添加到ID = 1的用户? “bulk_insert”gem可以做一些更新操作,或者为此我会做其他的事情? – matiss

+0

在单个查询中删除和创建比我熟悉的更复杂的SQL。 –

+0

在rails中已经有'update_all'和'delete_all'了,就我所知,插入内容并不相似。 –

相关问题