私は、ユーザーとワークスペースの間に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(id: 2).first.modelN(id:3).first.modelNplus1.create!(name: "txt")
私の最後の質問があり、これは正しい方法です:
u.workspaces(id: 1).first.groups.create!(name: "txt")
は今、私はより多くの団体があるとします。「最初の」追加最終的なコードがあるので、問題を解決しましたか?
問題はRailsがユーザーからグループをワークスペース何に出て見つけることができないということであるも、あなたがする場合(に追加する必要があります作成時にworspace_idを指定します)。 グループを作成するときにワークスペースIDを知っているので、単純に 'u.workspaces(id:1).groups.create!(name:" txt ")'で作成できません。 このようにして、適切なユーザーのワークスペースのグループを作成することができます。 (私は答えとしてこれを入力します) – evedovelli
ただ答えを更新しました。モデルの正しいIDで検索するには 'find_by_id'を使います。 'first'は常に最初の項目をリストから返します。これはあなたが望むものではありません。 – evedovelli