Rails order by association field

Solution 1:

Try this:

@users = User.includes(:user_extension).order("user_extensions.company desc")

I think you need at order: user_extensions, not user_extension

Solution 2:

Merge can make the query smaller/saner-looking, and it benchmarked faster for me in Rails 4.x:

@users = User.joins(:user_extension).merge(UserExtension.order(company: :desc))

Solution 3:

@users = User.order("user_extension.company desc") should work fine.

Solution 4:

Old topic, and perhaps off topic, but I needed this. FWIW:

Order by association field

User.includes(:user_extension).order('user_extensions.company ASC')

Lets make it more interesting, create more associations.

Order by the associations two levels deep.

User.includes(user_extension: :company).order('companies.name ASC')

Order by the associations three levels deep.

User.includes(user_extension: { company: :guilds }).order('guilds.secret_knock ASC')

Solution 5:

Maybe too late but I ran into a similar issue and this is how I implement it:

scope :sort_by_company, ->{
    joins(:user_extension).order(UserExtension.arel_table[:company].lower.desc)
  }

The code above should be placed within the user model.

Hope it can help! 👍