获得投票最多的Mongoid和rails(类似于count和group by)

时间:2012-09-27 13:41:41

标签: ruby-on-rails-3 mapreduce mongoid

我有三个文件

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

在Voto文档中,字段值是1到5之间的数字

所以我需要获得最多投票的照片才能展示......

我怎样才能实现这个目标?

由于

1 个答案:

答案 0 :(得分:0)

你也可以通过查询来做到这一点,但这需要花费一些时间,性能会降低。另一种解决方案是在模型图片中创建一个字段total_votos,每当对图片进行投票时,将字段值添加到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

,您只需运行查询即可找到最大值

Picture.where(:max_votes => Picture.all.max(:total_votes))