如何计算和按人气排序?

时间:2014-07-29 02:15:13

标签: ruby-on-rails will-paginate popularity

我正在努力为我的显示选项添加最受欢迎的选项。我不确定这个等式是否是我想要使用的等式,但我认为数学是我问题中不敬的部分,但是对于建议的改进是免费的。

我的问题是“@ cards.pop =(@ W + @R)+((1 - @W)* @ R0)”我得到一个“未定义的方法`pop ='为nil:NilClass”错误代码。我可以不,或者如何为字符串数组添加值,然后将其用作排序选项,例如其他“视图”选项有哪些?

也随意挑选你看到的任何其他东西。如果我从未被告知,我永远不会知道。

感谢大家提前帮助, 伊恩

if params[:view].present?
  if params[:view] == 'new' #Sort newest to oldest
    @cards = Card.order('created_at DESC').page(params[:page])
  elsif params[:view] == 'old' #Sort oldest to newest
    @cards = Card.order('created_at ASC').page(params[:page])
  elsif params[:view] == 'talk' #Sort most talked about
    @cards = Card.order('comments_count DESC').page(params[:page])
  elsif params[:view] == 'pop' #Sort most popular
    # http://math.stackexchange.com/questions/41459/how-can-i-calculate-most-popular-more-accurately
    @cards = Card.all
    @R0 = Card.average("score")
    @nMax = Card.maximum("votes_count")
    @cards.each do |card|
      @R = card.score
      @n = card.votes_count
      @W = @n / @nMax
      @cards.pop = (@W + @R) + ((1 - @W) * @R0)
    end
    # Need to add a Cards.order line - Not sure how to go about this.
  else
    @cards = Card.order('score DESC').page(params[:page])
  end
else
  @cards = Card.order('score DESC').page(params[:page])
end

卡表

 => Card(id: integer, user_id: integer, event: text, created_at: datetime, updated_at: datetime, score: integer, comments_count: integer, votes_count: integer)      

投票表

=> Vote(id: integer, user_id: integer, card_id: integer, up: boolean, created_at: datetime, updated_at: datetime)                                                                                   

1 个答案:

答案 0 :(得分:0)

您可以将(计算机流行度)代码的一部分移动到模型方法中:

class Article < ActiveRecord::Base
...
  def popularity
    @R0 = Card.average("score")
    @nMax = Card.maximum("votes_count")
    @R = score
    @n = votes_count
    @W = @n / @nMax
    (@W + @R) + ((1 - @W) * @R0)
  end
...
end

在那之后你就像那样收集:

elsif params[:view] == 'pop' #Sort most popular
  @cards = Card.all.sort{|a, b| a.popularity <=> b.popularity}
end