gwalshington
gwalshington

Reputation: 1495

Combine two ActiveRecord results and sort by a shared joined table attribute

I have a Convo table and a GroupMeeting table that both are associated with a Msg table.

I want to find all the instances where the current_user has convos or group_meetings with msgs, combine the two, and then show both together to the user in order of the last msg.created_at

Here I have defined both:

@convos = Convo.includes(:msgs).where("sender_id = ? OR recipient_id = ?", current_user, current_user).where.not(:msgs => { :id => nil }).merge(Msg.order(created_at: :desc))
@group_meetings = current_user.group_meetings.includes(:msgs).where.not(:msgs => { :id => nil }).merge(Msg.order(created_at: :desc))

And then combined them together:

  @convos = @convos + @group_meetings

What I can't figure out is how to now sort them by msg.created_at

I have tried the following:

 @convos = (@convos + @group_meetings).sort_by(&:"#{msg.created_at}")
 @convos.order('msg.created_at DESC')

These all seem to be server-side sorting though. How can I sort these based off the join table, after the array has been created?

Please let me know if I need to supply any other details. Thank you!!

Upvotes: 2

Views: 719

Answers (1)

potashin
potashin

Reputation: 44581

You can try the following:

(@convos + @group_meetings).sort_by { |item| item.msgs.minimum(:created_at) }

Upvotes: 2

Related Questions