0

我有一個分類模型,圖像模型和用戶模型排序在有許多通過

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名用戶排名前25位用戶,1類和2
+0

我覺得有一個類似的問題在這裏:http://stackoverflow.com/questions/ 1760404/order-products-by-association-count – 2012-03-31 13:10:51

+0

@BenMiller no是has_many關係,其中排序基於列值,但我需要根據該類別中的圖像數量進行排序,該用戶 – 2012-03-31 13:15:01

+0

是否嘗試過將order域添加到關係中? – 2012-03-31 13:23:43

回答

0

嘗試這樣做:

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

這會給你上的有序陣列25個用戶ID將圖像發佈到該類別。

要做到這一切在一個查詢中,我相信你會需要做更復雜的選擇(通過SQL找到)