2012-09-27 26 views
0

我有三個文件獲得最多投票與Mongoid扶手(像計數和GROUP BY)

class User 
    include Mongoid::Document 
    has_many :votos 
    ... 
    ... 
end 

class Picture 
    include Mongoid::Document 
    has_many :votos 
    belongs_to :user 
    ... 
    ... 
end 

class Voto 
    include Mongoid::Document 
    belongs_to :picture 
    belongs_to :user 
    field :value => :type => Integer 
    ... 
    ... 
end 

在博託文件,該字段值爲1和5

所以之間的數字。我需要得到所有顯示最多投票的圖片...

我該如何做到這一點???

感謝

回答

0

您可以通過查詢也做到這一點,但它會採取一個時間地獄和性能將會下降。另一種方案是在模型圖片創建一個字段total_votos,每當一個投票給一個畫面只是運行查詢

Picture.where(:max_votes => Picture.all.max(:total_votes)) 
字段值添加到total_votes

class Picture 
    include Mongoid::Document 
    has_many :votos 
    belongs_to :user 
    field :total_votes,:type => Integer 
    ... 
    ... 
end 

class Voto 
    include Mongoid::Document 
    belongs_to :picture 
    belongs_to :user 
    field :value => :type => Integer 
    after_create do 
     picture = self.picture 
     picture.total_votes += self.value 
     picture.save 
    end 
    ... 
    ... 
end 

,你可以找到的最大值

+0

有幫助嗎? – abhas