我正在尝试在 ActiveRecord 中创建多态模型。它应该与任何类型的另一个对象具有一对一的关系。我正在关注Understanding Polymorphic Associations in Rails来自 LaunchSchool 的博客文章。
我的迁移:
# 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
。
我的模型类:
# 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
关系可以是任何类型)。为什么它在那里?我做错了什么?
最佳答案
您的迁移看起来没问题,我很难想象 ActiveRecord
本身提供的这种行为。更重要的是,由 Rails
自动生成的外键可能会被命名为 index_reasons_on_event_id
,而不是 fk_reasons_event_id
。
在我看来,这里有一些幕后的事情,比如修补ActiveRecord::ConnectionsAdapters
,如here所述。 .
我建议检查初始化文件中是否有一些令人讨厌的猴子补丁,可能还检查一下 Gemfile 中是否有类似 automatic_foreign_key
或 schema_plus
的内容,它们可以自动从列名和关系推断外键.
关于ruby-on-rails - 为什么 ActiveRecord 对我的新表设置了不需要的外键约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441262/