我正在建立医生预约网站。我有用户模型,我想把它分成两部分:医生和病人。我试过了:
class User < ActiveRecord::Base
end
class Appointment < ActiveRecord::Base
belongs_to :physician, class_name: "User"
belongs_to :patient, class_name: "User"
end
class Physician < User
has_many :appointments
has_many :patients, through: :appointments, source: "User"
end
class Patient < User
has_many :appointments
has_many :physicians, through: :appointments, source: "User"
end
问题:如何在appointsments表中获取physician_id和patient_id列? 我选择了这种方式,因为当医生和患者模型分开时,注册将是问题(我想是这样......)。
答案 0 :(得分:0)
我认为您正走在正确的道路上,只需要进行迁移即可在约会表上添加对医生和患者的引用。 虽然,您不需要将源属性添加到患者或医生中,因为Rails会推断出这些属性!
我认为我也更喜欢采用医生和患者模型的这种方法,虽然不是为了注册目的,而是为了单一责任!
如果有效,请告诉我
答案 1 :(得分:0)
add_reference :appointments, :patient, foreign_key: true
add_reference :appointments, :physician, :foreign_key: true
这两次迁移应该为表添加外键。检查文档以确保我的语法绝对正确。
答案 2 :(得分:0)
除了建议的更改dpalazzari
之外,我相信您还需要进行以下更改:
class Appointment < ActiveRecord::Base
belongs_to :physician, class_name: "Physician", inverse_of: :appointments
belongs_to :patient, class_name: "Patient", inverse_of: :appointments
end
class Physician < User
has_many :appointments, foreign_key: :physician_id, inverse_of: :physician
has_many :patients, through: :appointments, source: "User"
end
class Patient < User
has_many :appointments, foreign_key: :patient_id, inverse_of: :patient
has_many :physicians, through: :appointments, source: "User"
end