Let’s say I’ve got the following (simplified) data model:
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
I know can get a all of location’s event dates simply:
Location.event_dates
But how can I scope the query to just get, for example, event dates with available spots? i.e.
Location.event_dates.where(available_spots > 0)
Since available_spots is a calculated value and not an actual database field of EventDate, that doesn’t seem possible. I was hoping to avoid adding those calculation methods to the DB itself, but if it’s the only way….
Thanks in advance!
Ok, looks like the answer was hiding in plain sight (as usual), under the Extensions section of the Mongoid documentation:
Relations – Common Behavior: Extensions
Two part answer:
First, the method I want is
select, notwhere, so while I can’t do what I proposed above, I can do:To “scopify” that (in essense), what I want is to extend the relation as defined in Location as follows:
So now I can call, simply:
Et voila.