我在用戶和工作區之間有一個HABTM關聯,它們也有組。問題是我無法從用戶插入數據介紹組。通過HABTM插入數據
class User < ActiveRecord::Base
has_and_belongs_to_many :workspaces #, dependent: :destroy
has_many :groups, through: :workspaces
end
class Workspace < ActiveRecord::Base
has_and_belongs_to_many :users, dependent: :destroy
has_many :groups, dependent: :destroy
end
這是連接表遷移:
class CreateUsersAndWorkspaces < ActiveRecord::Migration
def change
create_table :users_workspaces, id: false do |t|
t.belongs_to :user, index: true
t.belongs_to :workspace, index: true
end
end
end
在軌控制檯,當我嘗試創建新組:
u.groups.create!(name: "txt", workspace_id: 1)
(0.1ms) begin transaction
(0.2ms) rollback transaction
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly:
Cannot modify association 'User#groups' because it goes
through more than one other association.
有沒有辦法從用戶創建羣組?
編輯: 在@evedovelli的幫助下,我可以讓它工作。但由於user.workspace是一個ActiveRecord_Associations_CollectionProxy,它不是一個工作區類,而是一個集合。追加「第一」,解決了這個問題,所以最後的代碼是:
u.workspaces(id: 1).first.groups.create!(name: "txt")
現在假設我有更多的關聯:
u.workspaces(id: 1).first.groups(id: 2).first.modelN(id:3).first.modelNplus1.create!(name: "txt")
我的最後一個問題是,這是正確的方法是什麼?
問題是Rails的無法找出什麼工作區中的組從用戶應加(即使你像創建時那樣在創建時指定worspace_id)。 由於您在創建組時已經知道了工作空間ID,您不能簡單地使用'u.workspaces(id:1).groups.create!(name:「txt」)''創建嗎? 這樣可以爲正確的用戶工作區創建組。 (我會輸入這個答案) – evedovelli
剛剛更新了答案。使用'find_by_id'通過模型中的正確標識進行搜索。 'first'將總是返回列表中的第一個項目,這不是你想要的。 – evedovelli