class Appointment < ApplicationRecord
belongs_to :teacher
belongs_to :student
end
class Teacher < User
has_many :appointments
end
class Student < User
has_many :appointments
end
class User < ApplicationRecord
has_secure_password
validates :username, presence: true
validates :username, uniqueness: true
validates :username, length: { minimum: 4 }
validates :email, presence: true
validates :email, uniqueness: true
end
架构:
ActiveRecord::Schema[7.0].define(version: 2024_06_06_180259) do
create_table "appointments", force: :cascade do |t|
t.datetime "start_datetime"
t.integer "teacher_id", null: false
t.integer "student_id", null: false
t.string "notes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "status"
t.index ["teacher_id"], name: "index_appointments_on_teacher_id"
t.index ["student_id"], name: "index_appointments_on_student_id"
end
create_table "teachers", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "students", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "username"
t.string "password_digest"
t.string "first_name"
t.string "last_name"
t.string "type"
t.string "phone_number"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_foreign_key "appointments", "teachers"
add_foreign_key "appointments", "students"
end
我之前在使用 STI 在同一个用户数据库表中代表教师和学生时遇到问题。但现在我为教师和学生制作了单独的表格。尽管如此,我还是收到了外键约束失败错误。我不确定我在这里做错了什么。看起来我的联想是正确的。有人可以指导我吗?
您可以将教师和学生分成具有相同支持
users
表的不同模型。这是一种常见的模式。尽管如此,我只会在教师和学生之间存在逻辑差异的情况下才会这样做(目前在您的示例中未证明)。
如果执行此操作,则无需在数据库中创建
teachers
表或 students
表。如果不这样做更好。
Rails 假设 当您使用
belongs_to
时,标识符是表名称,但您可以覆盖它。
class Appointment < ApplicationRecord
belongs_to :teacher, class_name: "User"
belongs_to :student, class_name: "User"
end
上面的内容会告诉 Rails 在
teacher_id
列上查找 student_id
和 users.id
,并且应该可以解决您的外键约束问题。