【问题标题】:Get the most voted with Mongoid and rails (something like count and group by)使用 Mongoid 和 rails 获得最多投票(例如 count 和 group by)
【发布时间】:2012-09-27 13:41:40
【问题描述】:

我有三个文件

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

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

我怎样才能做到这一点???

谢谢

【问题讨论】:

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


    【解决方案1】:

    您也可以通过查询来做到这一点,但这需要很长时间,而且性能会下降。另一种解决方案是在模型图片中创建一个字段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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      相关资源
      最近更新 更多