我有 2 个模型需要引用,但第一个模型是自参照关联

I have 2 models need to references, but first model is a self-referential association

提问人:Patrick Su 提问时间:4/17/2023 更新时间:4/17/2023 访问量:32

问:

我的实验室

rails new test1 -d mysql
rails g scaffold User name
rails g migration AddTeacherToUsers #add_reference :users, :teacher, index: true 
rails g scaffold Lab name user:references
rails db:create db:migrate

系统消息

创建的数据库“test1_development” 已创建数据库“test1_test” 20230416164900 CreateUsers:迁移 == create_table(:users) 0.1837秒 20230416164900 CreateUsers:已迁移 (0.1839s) ==

20230416164941 AddTeacherToUsers:迁移 == add_reference(:用户, :老师, {:index=>true}) 0.4567秒 20230416164941 AddTeacherToUsers:已迁移 (0.4568s) ==

20230416165121 CreateLabs:迁移 == create_table(:labs) 0.4219秒 20230416165121 CreateLabs:已迁移 (0.4221s) ==

rails g migration AddTeacherToLabs teacher:references
vi apps/models/lab.rb # belongs_to :teacher, class_name: "User"
rails db:migrate

这是错误消息:

20230416165540 AddTeacherToLabs:迁移 == add_reference(:实验室, :老师, {:foreign_key=>true}) Rails 中止了! StandardError:发生错误,所有后续迁移均已取消:

mysql2::错误:表“test1_development.teachers”不存在:显示来自 /home/patrick/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:in <top (required)>“ 的完整字段 /home/patrick/test1/bin/spring:15:in load' bin/rails:3:in ''teacherschange' /home/patrick/test1/bin/rails:9:in <top (required)>' bin/rails:3:in

引起: ActiveRecord::StatementInvalid:Mysql2::Error:表“test1_development.teachers”不存在:显示 /home/patrick/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:in <top (required)>” /home/patrick/test1/bin/spring:15:in load' bin/rails:3:in ''teacherschange' /home/patrick/test1/bin/rails:9:in <top (required)>' bin/rails:3:in

引起: Mysql2::Error:表“test1_development.teachers”不存在 /home/patrick/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:in <top (必需)>' /home/patrick/test1/bin/spring:15:in load' bin/rails:3:in ''change' /home/patrick/test1/bin/rails:9:in <top (required)>' bin/rails:3:in

引起: Mysql2::Error:无法创建表。(errno: 150 “外键约束格式不正确”) /home/patrick/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:in <top (必需)>' /home/patrick/test1/bin/spring:15:in load' bin/rails:3:in '' 任务:TOP => db:migrate (通过使用 --trace 运行任务来查看完整跟踪)test1_developmentlabschange' /home/patrick/test1/bin/rails:9:in <top (required)>' bin/rails:3:in

我该怎么办?感谢您的帮助。

Ruby-on-Rails 关联自 引用

评论


答:

0赞 max 4/17/2023 #1

如果要列指向用户表,则需要在迁移中显式配置外键:teacher_id

class AddTeacherToLabs < ActiveRecord::Migration[7.0]
  def change
    add_reference :labs, :teacher, 
       null: false, 
       foreign_key: { to_table: :users }
  end
end

我认为您不能从生成器中添加此选项。

评论

0赞 Patrick Su 4/17/2023
非常感谢您的帮助,这个问题已经困扰了我一个星期了!
0赞 Patrick Su 4/18/2023
我发现了一个新问题!Lab.first.teacher 不是一个完整的模型,所以我无法访问 Professor.count、Professor.name 或其他任何东西,我只能使用 professor_id :(
0赞 max 4/18/2023
这是一个单独的问题。