Ruby 根据创建的主题、喜好和评论数对主题进行排名

Ruby 根据创建的主题、喜好和评论数对主题进行排名,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,我正在寻找一种方法来对用户发布的主题进行排名。我现在正在使用这个: Topic.select("topics.*, (((topics.likes_count - 1) / POW(((EXTRACT(EPOCH FROM (now()-topics.created_at)) / 3600)::integer + 2), 1.5))) AS popularity").order("popularity DESC") 我想知道如何增加每个主题的评论数量 topics.rb has_many :c

我正在寻找一种方法来对用户发布的主题进行排名。我现在正在使用这个:

Topic.select("topics.*, (((topics.likes_count - 1) / POW(((EXTRACT(EPOCH FROM (now()-topics.created_at)) / 3600)::integer + 2), 1.5))) AS popularity").order("popularity DESC")
我想知道如何增加每个主题的评论数量

topics.rb

has_many :comments, as: :commentable, dependent: :destroy
has_many :commenters, through: :comments
comments.rb

belongs_to :user
belongs_to :commentable, polymorphic: true, touch: true
belongs_to :commenter, class_name: 'User', foreign_key: :user_id
user.rb

has_many :comments, :dependent => :destroy
has_many :topics #destroyed via the UserDeletionService

只需在主题模型中添加一个名为
comments\u counter
的列,然后将comments.rb更改为包含
counter\u cache:true
,以将
所属的主题关联包括在内

更多信息,请向下滚动至计数器缓存:


计数器缓存在数据库上的开销要少得多,而且比动态计算每个主题的评论数要省事得多

只需在主题模型中添加一个名为
comments\u counter
的列,然后将comments.rb更改为包含
所属主题关联的
计数器缓存:true

更多信息,请向下滚动至计数器缓存:

计数器缓存在数据库上的开销要少得多,而且比动态计算每个主题的评论数更省事