Rails - 如何创建与单表继承的 2 个子类部分的关联

问题描述 投票:0回答:1

所以我设置了单表继承,这样我就可以为用户表创建两个子类。在我当前的实现中,两个子类将具有完全相同的字段,因此我认为 STI 在这里有意义。

    class User < ApplicationRecord
    end

    class Student < User
    end

    class Teacher < User
    end

    class Appointment < ApplicationRecord
    end

我想创建一个预约模型,该模型与学生具有多对一关联,并且与教师具有多对一关联。但由于学生和教师属于同一个用户表,我将如何创建数据库迁移来与这些模型建立关联?

    class CreateAppointments < ActiveRecord::Migration[7.0]
      def change
        create_table :appointments do |t|
          t.datetime :start_datetime
          t.references :users, null: false, foreign_key: true
#         t.references :users, null: false, foreign_key: true  --> this one should be for students
          t.timestamps
        end
      end
    end

我继续使用 STI 有意义吗?或者我现在应该为学生和教师创建单独的表格吗?目前这对我来说没有多大意义,因为它们具有完全相同的字段。但这样一来,预约关联就会变得容易得多。

ruby-on-rails ruby model-view-controller activerecord single-table-inheritance
1个回答
0
投票

好吧,我现在很惊讶地发现答案一直在我的脑海中。我需要做的迁移:

 class CreateAppointments < ActiveRecord::Migration[7.0]
  def change
    create_table :appointments do |t|
      t.datetime :start_datetime
      t.references :teacher, null: false, foreign_key: true
      t.references :student, null: false, foreign_key: true
      t.timestamps
    end
  end
end

我以为你只能通过 t.references 引用带有表的模型,但是通过使用子类

teacher
student
,Rails 知道在
users
表中查找这些关联。

© www.soinside.com 2019 - 2024. All rights reserved.