Rails SQL sort by inner has_one association field

57 Views Asked by At

Every User has one active account. How do i use sql to sort all Users by the updated_at field in active_account?

class User < ApplicationRecord
  has_one :active_account, -> { order('created_at DESC').where(status_code: 'active') }, class_name: 'Account'
end
1

There are 1 best solutions below

0
Joel Blum On
User.joins(:account).order("accounts.created_at DESC")

I'm not 100% sure but you might also just use the association scope, if this works this is obviously better:

User.joins(:active_account)