【问题标题】:How to calculate and sort by popularity?如何计算和按人气排序?
【发布时间】:2014-09-20 08:22:42
【问题描述】:

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

我的问题是“@cards.pop = (@W + @R) + ((1 - @W) * @R0)”我得到一个“未定义的方法 `pop=' for 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)                                                                                   

【问题讨论】:

  • 您的 @cards 中某处有 nil...尝试在 rails 控制台中检查或删除所有卡并仅使用 1 张卡,确保没有空卡
  • @railsdevmtl 这是我缺少流行专栏。每次页面加载时,我都试图做到这一点而不写。也许我想太多,也许我做错了。我添加了该列,只有 11 个条目,它的加载时间明显变慢了。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多