Hannah__
Hannah__

Reputation: 1

Rails SQL sort by inner has_one association field

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

Upvotes: 0

Views: 74

Answers (1)

Joel Blum
Joel Blum

Reputation: 7888

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)

Upvotes: 0

Related Questions