无法在关系表

时间:2016-06-20 08:30:02

标签: ruby-on-rails postgresql activerecord rails-activerecord

我有两种模式:

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

class Bracket < ActiveRecord::Base
  has_many :bracket_matches

  # Has a STI column
end

我正在尝试向表bracket_matches添加外键。

add_foreign_key :bracket_matches, :brackets

引发以下错误

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")

我做错了什么,为什么要检查bracket_id而不是brackets上的bracket_matches

2 个答案:

答案 0 :(得分:1)

rails g migration AddFieldToBracketMatches bracket:references 检查您的迁移文件,然后检查rake db:migrate

修改

在这种情况下,为什么不只是rails g migration RemoveColumnFromBrackMatches,remove_column:bracket_matches,:bracket,rake db:migrate,然后删除这些迁移文件并创建我上面建议的迁移

答案 1 :(得分:0)

添加索引:像这样

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