Dan Andreasson
Dan Andreasson

Reputation: 16202

Can't add foreign key on relation table

I have two models:

class BracketMatch < ActiveRecord::Base
  belongs_to :match
  belongs_to :bracket
end

and

class Bracket < ActiveRecord::Base
  has_many :bracket_matches

  # Has a STI column
end

I am trying to add a foreign key to the table bracket_matches.

add_foreign_key :bracket_matches, :brackets

Raises the following error

PG::ForeignKeyViolation: ERROR:  insert or update on table "bracket_matches" violates foreign key constraint "fk_rails_39684e0d9b"
DETAIL:  Key (bracket_id)=(122) is not present in table "brackets".
: ALTER TABLE "bracket_matches" ADD CONSTRAINT "fk_rails_39684e0d9b"
FOREIGN KEY ("bracket_id")
REFERENCES "brackets" ("id")

What am I doing wrong and why is it checking bracket_id on brackets instead of bracket_matches?

Upvotes: 0

Views: 403

Answers (2)

RuNpiXelruN
RuNpiXelruN

Reputation: 1920

rails g migration AddFieldToBracketMatches bracket:references Check your migration file and then rake db:migrate

Edit

In that case why not just rails g migration RemoveColumnFromBrackMatches , remove_column :bracket_matches, :bracket , rake db:migrate, then delete both those migration files and create the migration I suggested above

Upvotes: 1

abhi110892
abhi110892

Reputation: 300

Add index:true like this

add_foreign_key :bracket_matches, :brackets ,index:true,foreign_key:true

Upvotes: 0

Related Questions