Rails order by association field

前端 未结 4 1116
慢半拍i
慢半拍i 2020-12-29 00:56

I have the following models

class User
  attr_accesible :first_name, :phone_number
  has_one :user_extension
end

class UserExtension
  attr_accessible :comp         


        
相关标签:
4条回答
  • 2020-12-29 01:41

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

    0 讨论(0)
  • 2020-12-29 01:46

    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')
    
    0 讨论(0)
  • 2020-12-29 01:47

    Try this:

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

    I think you need at order: user_extensions, not user_extension

    0 讨论(0)
  • 2020-12-29 01:47

    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))
    
    0 讨论(0)
提交回复
热议问题