rails 4 - 按投票数排序

时间:2013-11-30 07:24:45

标签: ruby-on-rails ruby ruby-on-rails-4

所以...我有图像。那些图像都有投票权。

我目前有 image.rb

class Image < ActiveRecord::Base
  belongs_to :user
  belongs_to :event

  has_many :image_votes, dependent: :destroy

  default_scope { order(ci_lower_bound) }

  def taken_by? (photographer)
    self.user == photographer
  end

  def self.ci_lower_bound
    pos = image_votes.where(value: 1).size
    n = image_votes.size
    if n == 0
      return 0
    end
    z = 1.96
    phat = 1.0*pos/n
    (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)
  end
end

我一直在玩这个...让默认范围工作的唯一方法是使用自己的方法。我在http://www.evanmiller.org/how-not-to-sort-by-average-rating.html找到了公式 - 我怎么称呼它才能使它工作?

1 个答案:

答案 0 :(得分:0)

我会在这个新专栏中创建一个名为by_votes的新范围,包括sum()order

scope :by_votes, -> { select("#{Image.table_name}.*, sum(#{ImageVote.table_name}.votes) AS votes").order("votes DESC") }