如何在的has_many关系进行排序的Rails AR.find的物体的数量物体、数量、关系、如何在

由网友(滁ㄋωǒ 谁乜卟准疼伱)分享简介:我怎么能写一个AR查找查询已下令由记录中的has_many关联多少?How can I write an AR find query to have the results ordered by the number of records in a has_many association?class User <...

我怎么能写一个AR查找查询已下令由记录中的has_many关联多少?

How can I write an AR find query to have the results ordered by the number of records in a has_many association?

class User < ActiveRecord::Base
  has_many :photos
end

我想要做这样的事情......

I want to do something like...

User.find(:all, :order => photos.count)

我知道我的发现是无效的code。说我有以下数据。

I realize my find is not valid code. Say I have the following data.

User 1, which has 3 photos 
User 2, which has 5 photos 
User 3, which has 2 photos

我想我找到给我带回来的用户在......的顺序

I want my find to bring me back the users in the order of...

User 2, 
User 1, 
User 3

基于的用户的照片的计

based on the count of of the users photos

推荐答案

如果您不希望一个额外的列,你总是可以要求在返回的结果集一个额外的列:

If you don't want an extra column, you could always ask for an extra column in the returned result set:

User.all(:select => "#{User.table_name}.*, COUNT(#{Photo.table_name}.id) number_of_photos",
         :joins => :photos,
         :order => "number_of_photos")

这将生成的SQL语句:

This generates the following SQL:

SELECT users.*, COUNT(photos.id) number_of_photos
FROM `users` INNER JOIN `photos` ON photos.user_id = users.id
ORDER BY number_of_photos
阅读全文

相关推荐

最新文章