为什么 ActiveRecord 对我的新 table 做了不需要的外键约束?

Why does ActiveRecord make an unwanted foreign key constraint on my new table?

我正在尝试在 ActiveRecord 中制作多态模型。它应该与任何类型的另一个对象具有一对一的关系。我正在关注 LaunchSchool 的 Understanding Polymorphic Associations in Rails 博客 post。

我的迁移:

# Expresses an explanation for an action or event
class CreateReasons < ActiveRecord::Migration
  def change
    create_table :reasons do |t|
      t.string :description
      t.integer :event_id
      t.string :event_type

      t.timestamps
    end
  end
end

请注意,我不是呼叫add_foreign_key

我的模型class:

# Expresses an explanation for an action or event
class Reason < ActiveRecord::Base
  belongs_to :event, polymorphic: true
end

如果我删除这一行,也会出现同样的错误。

当我运行 rake db:migrate(有或没有bundle exec)时,我得到一个错误,我认为是因为外键约束:

D, [2016-04-05T22:40:41.389615 #45464] DEBUG -- :    (9.7ms)  CREATE TABLE "reasons" ("id" serial primary key, "description" character varying(255), "event_id" integer, "event_type" character varying(255), "created_at" timestamp, "updated_at" timestamp, CONSTRAINT fk_reasons_event_id FOREIGN KEY ("event_id") REFERENCES "events" ("id"))
E, [2016-04-05T22:40:41.390720 #45464] ERROR -- : PG::Error: ERROR:  relation "events" does not exist
: CREATE TABLE "reasons" ("id" serial primary key, "description" character varying(255), "event_id" integer, "event_type" character varying(255), "created_at" timestamp, "updated_at" timestamp, CONSTRAINT fk_reasons_event_id FOREIGN KEY ("event_id") REFERENCES "events" ("id"))
D, [2016-04-05T22:40:41.391245 #45464] DEBUG -- :    (0.2ms)  ROLLBACK

我不知道这个约束是从哪里来的,我不认为我想要它,因为这个关系应该是多态的(event 关系可以是任何类型)。为什么它在那里?我做错了什么?

Rails 引导文件迁移的不同写法。 SEE

class CreateReasons < ActiveRecord::Migration
  def change
    create_table :reasons do |t|
      t.string :description
      t.references :event, polymorphic: true, index: true
      t.timestamps
    end
  end
end

我在rails的早期版本中使用了您问题中提到的方式。

您的迁移似乎没问题,我很难想象 ActiveRecord 本身提供的这种行为。不仅如此,由 Rails 自动生成的外键可能会被命名为 index_reasons_on_event_id,而不是 fk_reasons_event_id.

在我看来,这里有一些事情在幕后发生,比如修补 ActiveRecord::ConnectionsAdapters,如 here 所述。

我建议检查初始化文件是否有一些讨厌的猴子补丁,可能还有你的 Gemfile 是否有类似 automatic_foreign_keyschema_plus 的东西,它们可以自动从列名和关系中推断出外键。