在 Rails 中关联 3 个模型

Associating 3 Models in Rails

我对应该在我的应用程序中设置哪种类型的关联感到有点困惑。

我有这三个模型:Booking、Availability 和 Facility

某设施提供 1 小时的可用时间块。所以我会说 Availability: belongs_to :facility.

我试图表示一个预订可能有很多空房。如果我从下午 1 点到 3 点预订,那是两个 1 小时的时间段,我希望在预订 table.

的 1 条记录中表示

我在想我应该设置Bookings: has_many :availability
但后来我阅读了有关 has_many though 的内容,我不确定这样做是否更合适 Facilities has many Bookings through Availability...?

我绝对会在这里做一个 has_many :through 关联,但我会让 AvailabilityBooking 之间的关联与典型的 has_many :through 关联略有不同:

class Facility < ActiveRecord::Base
  has_many :availabilities
  has_many :bookings, through: :availabilities
end

class Availability < ActiveRecord::Base
  belongs_to :facility
  has_one :booking
end

class Booking < ActiveRecord::Base
  belongs_to :availability
end

我更喜欢这种关联方式的原因是因为在典型的 has_many :through 中,您有两个实体通过第三方实体彼此共享关系(例如,患者和医生共享关系 through名为 Appointment 的实体,如 Rails guides 所述)。然而,这个例子是不同的,因为 Booking 不应该与 Facility 有任何积极的关系——这种关系应该只是一个开放的 Availability.[=22 的副产品=]