Rails 3: ActiveRecord query order across multiple tables, merging
Event has a date
Subevent belongs_to :event (has no date on its own! Inherits it through Event)A User can participate in both, an Event or a Subevent, independently.
Now, I would like to list all of User's participations combined, ordered by date of either the Event or the Subevent (which has no own date, mind you). How does the ActiveRecord query need to be constructed to achieve this?
Event and Subevent are polymorphic "attendable开发者_运维技巧s". There is a table "Attendances" with attendable_type, attendable_id, user_id.
EDIT:
I figured these single queries for each "attendable" do the job, only they need to be combined now, to merge the dates (Subevents in between Events when ordering):
@events = Event.joins(:attendances).where("attendances.attendable_type = ? AND attendances.user_id = ?", "Event", @user).order('events.startdate ASC')
@subevents = Subevent.joins(:attendances).includes(:event).where("attendances.attendable_type = ? AND attendances.user_id = ?", "Subevent", @user).order('events.startdate ASC, subevents.created_at ASC')
#=> Event 1
# Event 2
# Subevent 1
# Subevent 2
# …
Help still appreciated, thanks
精彩评论