Reputation: 747
I have classic has_many through
relationship where I need to be able to add multiple Companies to particular User. Models look like this:
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
In console I can add single record with this:
[1] pry(main)> user=User.find(7)
[2] pry(main)> user.accounts.create(company_id: 1)
How do I add, edit, delete multiple accounts for user in one query? I need to attach multiple Companies to User, then Edit / Remove if necessary.
So far I tried to implement array part from this tutorial, but somehow it does not work as obviously I'm doing something wrong here:
[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>
As I understand I need to create array somehow and then operate with that. I would appreciate any help here. Thank you!
Solution
If anyone needs, I solved my problem a bit differently. I used checkboxes from this tutorial and it works just fine for me.
Upvotes: 1
Views: 1405
Reputation: 26758
Here's an example with the 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
)
Upvotes: 1