これで終日私の脳を破壊しました。 pool_tournament_match
のhas_manyリレーションシップを作成して、それぞれのマッチに他の多くのマッチがあるようにしました。私は pool_tournament_match_relationships
というテーブルを作成しました。Rails自己参照has_many through:正しいレコードを追加していません
create_table :pool_tournament_match_relationships do |t| t.belongs_to :parent, class_name: 'PoolTournamentMatch', index: true t.timestamps end
pool_tournament_match.rb
has_many :pool_tournament_match_relationships, class_name: 'PoolTournamentMatchRelationship', foreign_key: :parent_id has_many :parents, through: :pool_tournament_match_relationships
だから、私はこれを行う際に、しかしmatch.pool_tournament_match_relationships.create(parent: anotherMatch)
ような何かを行うことができる必要があり、レコードが関係表に追加実際にはmatch
の値であり、anotherMatch
ではありません。したがって、たとえば、一致IDが1でanotherMatch IDが2の場合は、1が関係テーブルに入力されます。ここ
コンソールから出力された:parent_id
が入力した
m.pool_tournament_match_relationships.create(parent: m2)
INSERT INTO "pool_tournament_match_relationships" ("parent_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["parent_id", 1], ["created_at", 2016-11-08 21:51:29 UTC], ["updated_at", 2016-11-08 21:51:29 UTC]]
注意代わりM2のMのIDである1です。
irb(main):012:0> m.id => 1 irb(main):013:0> m2.id => 5
私はあなたの助けに感謝!
EDIT:関係テーブルのスキーマを追加します。 create_table "pool_tournament_match_relationships", force: :cascade do |t| t.integer "parent_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["parent_id"], name: "index_pool_tournament_match_relationships_on_parent_id", using: :btree end
あなたはpool_tournament_match_relationships'テーブル 'で唯一の外部キーを持っていますか? – idej
スキーマを追加しました。 parent_idには整数が1つしかないように見えます。 – okysabeni
あなたが持っている多人数関係は、あなたが 'parent_id'フィールドと' pool_tournament_match_id'フィールドの両方を持っていなければ動作しません。以下の例を参照してください。 – moveson