Patm
Patm

Reputation: 2075

Rails includes ordered by first associate of a has_many relationship

Having a tough time figuring out how to build this query in active record. I have the following two models:

class Event
  has_many :event_times
end

class EventTime
  belongs_to :event
end

EventTime has a start_time Timestamp. I want to select Events, using pagination and order them by EventTime start_time. So events that have EventTimes coming up soonest are first. I'm able to put together a query that gets Events ordered by EventTime, but using pagination results in differing number of records due to the fact that an Event can have multiple EventTimes.

The other solution is doing group_by and then applying the pagination to that result. But this requires loading all the EventTimes into memory which will not scale.

Upvotes: 3

Views: 522

Answers (1)

ahmacleod
ahmacleod

Reputation: 4310

Don't fear the join; it's fast as long as you have an index set for event_id on your event_times table. You can group by event and order by the minimum start time. Pagination can be achieved by passing offset and limit numbers to the query.

Event
  .select('event.*, MIN(event_times.start_time) AS min_start_time')
  .joins(:event_times)
  .group('event.id')
  .order('min_start_time')
  .offset(offset)
  .limit(limit)

Upvotes: 3

Related Questions