Reputation: 703
I have a join_table
that currently has the following columns:
- id
- table_a_id
- table_b_id
Attempting to add a foreign key constraint to join_table
for table_a_id
, I generate the following migration:
class AddTableIdForeignKeyConstraintToJoinTable < ActiveRecord::Migration[5.0]
def change
add_foreign_key :table_a, :join_table, column: :table_a_id, primary_key: "lng_id"
end
end
Error:
PG::UndefinedColumn: ERROR: column "question_id" referenced in
foreign key constraint does not exist
: ALTER TABLE "table_a" ADD CONSTRAINT
"fk_rails_4b0148d527"
FOREIGN KEY ("question_id")
REFERENCES "join_table" ("lng_id")
Questions
What does this line mean foreign key constraint does not exist
? Where is Rails looking for the foreign key
?
Upvotes: 0
Views: 661
Reputation: 6749
As per add_foreign_key , first argument should be the table in which the foreign key exists, second argument should be table name in which the corresponding primary key exists.
And, your error indicates foreign key does not exist where it should.
Try changing the migration to this:
def change
add_foreign_key :join_table, :table_a, column: :table_a_id, primary_key: "lng_id"
end
Upvotes: 0
Reputation: 2088
What the error means is that there is no column question_id
in table table_a
. The table that you are adding the foreign key to (join_table
) should be the first argument and primary key should point to id
column in table_a
Upvotes: 1