Pierre Olivier Tran
Pierre Olivier Tran

Reputation: 955

Rails : Order by attribute of a specific submodel

I'm trying to order an array using an attribute from a specific submodel. Let's say I've got a list of Users, each users got Trades, I'd like to order my Users by ordering them by last created Trade.

I tried with

@invoices = User.includes(:payments).order('payments.last.created_at')

but it seems like last is considered itslef as an attribute rather than as a function, which raises this error:

ERROR:  missing FROM-clause entry for table

Is there a way to order my Users as planned ?

Upvotes: 0

Views: 880

Answers (1)

DroidNoob
DroidNoob

Reputation: 1143

There is no need for the last method in this query if you want to order it in descending.

Intead use DESC inside order,

@invoices = User.includes(:payments).order('payments.created_at DESC')

Upvotes: 2

Related Questions