2017-04-04 51 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'了,就我所知,插入內容並不相似。 –

相關問題