I have an Event model with parent_id
and date
attributes:
Event.rb
has_many :children, :class_name => "Event"
belongs_to :parent, :class_name => "Event"
I have no issues calling event.parent
or event.children
. A child event never has a child itself.
I am trying to add a scope to this model so that I can return the child with the nearest future date for every parent. Something like:
scope :future, -> {
where("date > ?", Date.today)
}
scope :closest, -> {
group('"parent_id"').having('date = MAX(date)')
}
Event.future.closest ==> returns the closest child event from every parent
But the above :closest
scope is returning more than one child per parent.