我有School
,ClassTestType
和SessionBatch
模型
我想要class_test_types的belongs_to参考和学校的session_batch。所以我从生成器创建了迁移文件。
class AddSchoolToClassTestType < ActiveRecord::Migration[5.1]
def change
add_reference :class_test_types, :school, foreign_key: true
add_reference :class_test_types, :session_batch, foreign_key: true
end
end
迁移成功运行。但是当我尝试为“class_test_type”创建一个新记录时,它会抛出错误
PG::ForeignKeyViolation - ERROR: insert or update on table "class_test_types" violates foreign key constraint "fk_rails_dd78b971af"
DETAIL: Key (school_id)=(1) is not present in table "schools"
而创建session_batch的另一个引用没有任何错误。
schema.rb
create_table "class_test_types", force: :cascade do |t|
t.string "test_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "weight"
t.bigint "school_id"
t.bigint "session_batch_id"
t.index ["school_id"], name: "index_class_test_types_on_school_id"
t.index ["session_batch_id"], name: "index_class_test_types_on_session_batch_id"
end
我不明白为什么它只发生在School
模型的情况下。为什么它在学校表中寻找school_id
键,什么时候应该是id
。虽然,所有其他参考工作正常。我无法将学校引用到我的申请中的任何模型。
更新:
我确实有id = 1的学校。(看下面的截图)。我从current_school.id
中提取它所以它不能是一些不存在的值。
使用Apartment Gem时我遇到过类似的问题。
在创建引用迁移时,它使用方法add_reference :users, :associated_model_name, foreign_key: true
,实际上,生成具有默认索引和外键的模式。
我比较了在这种情况下生成的模式,以找到添加到该密钥的额外索引。因此尝试将迁移从add_reference更改为add_column。这解决了这个问题。
根据我的理解,你面临着这个问题,因为学校实际上是一个模式,你不能像使用其他关联一样直接创建索引。尝试删除默认情况下使用add_reference
方法创建的索引。