sqlite 创建方法中出现“FOREIGN KEY约束失败”错误

qyuhtwio  于 12个月前  发布在  SQLite
关注(0)|答案(1)|浏览(225)

我在控制器的create方法中得到一个无效的外键错误:

ActiveRecord::InvalidForeignKey in TytsController#create
SQLite3::ConstraintException: FOREIGN KEY constraint failed
app/controllers/tyts_controller.rb:7:in `create'

我检查了我的关联和控制器,认为它们设置正确:

class TytsController < ApplicationController

  def create
    if current_user.type == 'Student'
      @tyt = Tyt.new(tyt_params)
      @tyt.student_id = current_user.id
      @tyt.save
      redirect_to root_path
    else
      redirect_to root_path
    end
  end

  private

    def tyt_params
        params.permit(
          :student_id,
          :turkish_correct,
          :turkish_incorrect,
          :math_correct,
          .
          .
          .
          :chemistry_incorrect)
      end
  end
class Student < User
    attr_accessor :teacher_id

    has_many :connections, dependent: :destroy
    has_many :teachers, through: :connections, dependent: :destroy, foreign_key: "teacher_id"
    has_many :tyts, dependent: :destroy, foreign_key: "student_id"

end
class Tyt < ApplicationRecord

  belongs_to :student

end
ActiveRecord::Schema[7.0].define(version: 2023_08_01_092656) do

  create_table "students", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "tyts", force: :cascade do |t|
    t.integer "turkish_correct"
    t.integer "turkish_incorrect"
    t.integer "math_correct"
    .
    .
    .
    .
    t.integer "student_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["student_id"], name: "index_tyts_on_student_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "type"
    t.string "first_name"
    t.string "last_name"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

  add_foreign_key "tyts", "students"
end
tquggr8v

tquggr8v1#

你试图将一个类型为Usercurrent_user)的对象赋给student_id(必须是Student),因此你得到了外键冲突。

相关问题