0

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?

2
  • Did you get any solution to your issue ? Commented Dec 4, 2016 at 20:13
  • not yet @dkp. I got the initial error to go away but I am a bit confused about how referencing works. For example: now I am trying to add a foreign key constraint for table_b to the join table and getting the error that constraint "fk_rails_ff820b2696" for relation "join_table" already exists. This means that the method add_foreign_key does not do what I think it does. So now working on understanding. Commented Dec 4, 2016 at 20:16

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.