这是我面临的情况:
可以安排约会:
因此,每个约会“类型”的属性可能不同。
我正在考虑这些模型并将其与 STI 一起使用,但我不确定我是否走在正确的轨道上:
class Appointment < ActiveRecord::Base
class TodayAppointment < Appointment
class WeekAppointment < Appointment
class SpecificDateAppointment < Appointment
table :
string, Type #type of the appointment (TodayAppointment, WeekAppointment...)
datetime, When #data used when type field is "SpecificDateAppointment"
string, Something #used when type field is "TodayAppointment"
对此进行建模的最佳方法是什么?
这是单表继承的好选择吗?
更新
感谢@Mike,@SpyrosP 到目前为止的帮助。我想出了下面的选项。
这些是数据库表的“ View ”以及它们的外观。
哪一个看起来最合适?
------------------------------------------------------------------------
Option A--(Polymorphic Association)
------------------------------------------------------------------------
|patients | day_appointments | week_appointments
| appointment_type | data | data
| appointment_id | |
------------------------------------------------------------------------
Option B--(Child references parent) (What is this pattern called?)
------------------------------------------------------------------------
|patients | day_appointments | week_appointments
| | patient_id | patient_id
------------------------------------------------------------------------
Option C--(Polymorphic Association + Single Table Inheritance of appointments)
------------------------------------------------------------------------
|patients | appointments |
| appointment_type | type |
| appointment_id | day_data |
| | week_data |
------------------------------------------------------------------------
Option D--(Child references parent + Single Table Inheritance of appointments)
------------------------------------------------------------------------
|patients | appointments |
| | type |
| | day_data |
| | patient_id |
------------------------------------------------------------------------
最佳答案
你很接近,但看起来你可以从使用 Class Table Inheritance 中受益.我的理由是,每种具体类型都有不同的属性。
这是 Vanilla Ruby 中的一些示例代码。我相信这比我能给出的任何描述都更容易理解。
class Appointment
def persist
raise "Must be implemented."
end
end
class TodayAppointment < Appointment
def persist
TodayAppointmentMapper save self
end
end
class WeekAppointment < Appointment
def persist
WeekAppointmentMapper save self
end
end
class Mapper
def save aAppointment
raise "Must be implemented."
end
end
class TodayAppointmentMapper < Mapper
def save aAppointment
# Specfic Today Appointment persistence details.
end
end
class WeekAppointmentMapper < Mapper
def save aAppointment
# Specfic Week Appointment persistence details.
end
end
请注意每种具体类型能够透明地选择适当的映射器。考虑将其与 Dependency Injection 结合使用以便于测试。
关于model - 如何在 Rails 中建模 "appointments"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4542151/