0

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

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

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

提前感谢大家的帮助,伊恩

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)                                                                                   
4

1 回答 1

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
于 2014-07-29T08:00:07.327 回答