0

我有三个文件

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 之间的数字

所以我需要得到所有投票最多的照片来展示......

我怎么能做到这一点???

谢谢

4

1 回答 1

0

您也可以通过查询来做到这一点,但这将花费大量时间并且性能会降低。另一种解决方案是total_votos在模型 Picture 中创建一个字段,每当对图片进行投票时,将字段值添加到 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))
于 2012-09-28T11:37:32.083 回答