ruby-on-rails 我有2个模型需要引用,但第一个模型是自引用关联

kxe2p93d  于 2023-04-22  发布在  Ruby
关注(0)|答案(1)|浏览(134)

实验室

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:migrating == create_table(:users)0.1837s 20230416164900 CreateUsers:迁移(0.1839s)==
20230416164941添加教师到用户:migrating == add_reference(:users,:teacher,{:index=〉true})0.4567s 20230416164941 AddTeacherToUsers:迁移(0.4568s)==
20230416165121 CreateLabs:migrating == create_table(:labs)0.4219s 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添加教师到实验室:migrating == add_reference(:labs,:teacher,{:foreign_key=〉true})rails aborted!StandardError:发生错误,所有后续迁移已取消:
错误提示:表'test1_development.teachers'不存在:显示完整字段从teachers/home/帕特里克/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:in change' /home/patrick/test1/bin/rails:9:in〈top(required)〉' /home/patrick/test1/bin/spring:15:in <top (required)>' bin/rails:3:in load' bin/rails:3:in ' 原因:ActiveRecord::StatementInvalid:错误提示:表'test1_development.teachers'不存在:显示完整字段从teachers/home/帕特里克/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:inchange' /home/patrick/test1/bin/rails:9:in〈top(required)〉' /home/patrick/test1/bin/spring:15:in<top (required)>' bin/rails:3:inload' bin/rails:3:in'
原因:Mysql 2::错误:表'test1_development.teachers'不存在/home/帕特里克/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:in change' /home/patrick/test1/bin/rails:9:in〈top(required)〉' /home/patrick/test1/bin/spring:15:in <top (required)>' bin/rails:3:in load' bin/rails:3:in ' 原因:Mysql 2::错误:无法创建表test1_development.labs(错误号:150“外键约束格式不正确”)/home/帕特里克/test1/db/migrate/20230416165540_add_teacher_to_labs.rb:3:inchange' /home/patrick/test1/bin/rails:9:in〈top(required)〉' /home/patrick/test1/bin/spring:15:in<top (required)>' bin/rails:3:inload' bin/rails:3:in'任务:TOP =〉db:migrate(使用--trace运行任务查看完整跟踪)

我该怎么做?谢谢你的帮助。

pbwdgjma

pbwdgjma1#

如果你想让teacher_id列指向users表,你需要在迁移中显式配置外键:

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

我不认为你可以从生成器中添加此选项。

相关问题