Rails :HOw to order a table by associated model

风流意气都作罢 提交于 2019-12-13 06:43:23

问题


I think the problem is trivial. I have two models: User and Betting. User has_many :bettings

Betting belongs_to :user

I just want to get the users ordered by who made more bettings.


回答1:


Are you on Rails2 or Rails3?

On Rails3, you can use the Ruby sort method and something like:

User.includes(:bettings).sort{|x,y| x.bettings.size <=> y.bettings.size}

Of course, in this case the sorting occurs after the SQL request, which is not optimum if you have large tables… I'm trying to figure how to do it at the SQL level with no answer yet…



来源:https://stackoverflow.com/questions/3859951/rails-how-to-order-a-table-by-associated-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!