Search code examples
ruby-on-railsactiverecord

Ordering with nested association


I have an app with a nested association like this:

user has_many timesheets
timesheet has_many invoices

When showing the invoice index view, I want to order the invoices on the first_name of the user it belongs to. I can do an order on the immediate parent like this:

Invoice.joins(:timesheet).order('timesheets.user_id')

Is it possible to go one level higher?


Solution

  • Yes, it is:

    Invoice.joins(timesheet: :user).order('users.first_name')