排序有很多通过

时间:2012-03-31 13:01:01

标签: ruby-on-rails ruby-on-rails-3 sql-order-by has-many-through

我有一个类别模型,一个图像模型和一个用户模型

  Category:
      has_many :images
      has_many :users, :through=>'images'


  Image: 
    belongs_to :category, :counter_cache => true
    belongs_to :user

  User:
      has_many :images


   Category.first.users //returning users but its not ordering ie :order=>' images uploaded by users in that category DESC'.
   Category.all.collect(&:users)  //returning users but its not ordering ie :order=>' images uploaded by users in that category DESC'..
  • 我需要该类别的用户列表,前25位用户拥有该类别中的最大图片数量。
  • 我需要两个或更多类别中的前25位用户,例如类别1和2中的前25位用户。

1 个答案:

答案 0 :(得分:0)

尝试做:

Category.first.images.group(:user_id).count(:user_id, :order=>"count_user_id desc").map {|k,v| k}.first(25)

这将为您提供前25个用户ID的有序数组,将图像发布到该类别。

要在一个查询中执行此操作,我相信您需要执行更复杂的选择(通过sql查找)