PG :: ForeignKeyViolation-创建引用时错误记录

时间:2019-04-14 04:35:01

标签: ruby-on-rails postgresql activerecord foreign-keys migration

我有SchoolClassTestTypeSessionBatch模型

我想让所属学校引用class_test_types和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中提取它,因此它不能是某些不存在的值。

enter image description here

1 个答案:

答案 0 :(得分:1)

在使用Apartment Gem时,我也遇到了类似的问题。

在创建引用迁移时,它使用方法add_reference :users, :associated_model_name, foreign_key: true,该方法实际上会生成具有默认索引和外键的架构。

我比较了在这种情况下生成的架构,以找到添加到该键的额外索引。因此,尝试将迁移从add_reference更改为add_column。可以解决问题。

根据我的理解,您面临此问题,因为学校实际上是一个架构,您不能像在其他关联中创建的那样直接在其上创建索引。尝试删除默认情况下使用add_reference方法创建的索引。