假设我有以下(简化的)数据模型:
class Location
include Mongoid::Document
has_many :event_dates
end
class EventDate
include Mongoid::Document
has_many :event_sessions
belongs_to :location
def total_spots
self.event_sessions.sum("max_participants")
end
def booked_spots
self.event_sessions.sum("participants_count")
end
def available_spots
self.total_spots - self.booked_spots
end
end
class EventSession
include Mongoid::Document
belongs_to :event_date
field :max_participants
field :participants_count
end
我知道可以简单地获得所有地点的活动日期:
Location.event_dates
但是,我如何才能将查询范围限定为仅获取例如具有可用位置的事件日期?IE
Location.event_dates.where(available_spots > 0)
由于available_spots
是计算值而不是 的实际数据库字段EventDate
,因此这似乎是不可能的。我希望避免将这些计算方法添加到数据库本身,但如果这是唯一的方法......
提前致谢!