【问题标题】:ActiveRecord::StatementInvalid: SQLite3::SQLException: no such tableActiveRecord::StatementInvalid: SQLite3::SQLException: 没有这样的表
【发布时间】:2020-03-08 07:15:36
【问题描述】:

我是 Rails 新手,正在尝试制作一个简单的网络应用程序。

我生成了以下组​​件:

rails generate scaffold user username:string password:string
rails generate scaffold appointment doctor:references patient:references

在预约模型中,我将医生和病人的类指定为如下用户

# app/models/appointment.rb
class Appointment < ApplicationRecord
  belongs_to :doctor, :class_name => "User"
  belongs_to :patient, :class_name => "User"
end

我让其他一切保持不变,通过应用 rails db:migraterake db:test:prepare,我收到一条错误消息,说我没有桌子医生

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.doctors

但我认为 modify.rb 中的规范会为我完成这项工作。

我该如何进行这项工作?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    脚手架很可能在引用上生成了带有foreign_key: true 的迁移。

    检查 db/migrate/ 中的 create_appointments 迁移文件并将其删除。

    如果你想有一个外键添加:

    add_foreign_key :appointments, :users, column: :doctor_id
    add_foreign_key :appointments, :users, column: :patient_id
    

    https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key

    外键约束检查您设置的 id 是否存在于另一个表中。如果不是,创建记录时会崩溃。

    【讨论】:

    • 您能告诉我有关删除foreign_key: true 的更多信息吗?它们确实是foreign_keys,不是吗?
    • 迁移文件描述了对数据库的更改。 foreign_key: true 告诉它添加标准外键约束 -> google it ;) w3schools.com/sql/sql_foreignkey.asp 默认情况下,它将使用列名 a.k.a. doctor_id 并尝试猜测表 -> 医生。告诉它在答案中的代码中添加针对不同表?的约束
    【解决方案2】:

    doctor: referencespatient: references 将在 appointments 表中创建两列,doctor_idpatient_id 将分别引用 doctors 表和 patients 表。

    这并不奇怪,这些表不存在。要告诉迁移doctorpatient 实际上来自users 表,您需要在迁移中使用to_table

    db/migrate/ 中打开约会迁移文件,并为患者参考和医生参考添加to_table 选项:

    t.references :doctor, foreign_key: { to_table: :users }, index: true
    t.references :patient, foreign_key: { to_tabale: :users }, index: true
    

    to_table 用于当您想让列引用不同的表时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 2016-08-24
      • 2015-10-08
      • 2020-10-18
      • 2016-12-08
      相关资源
      最近更新 更多