按相关模型计数对记录排序,然后按时间顺序排序

时间:2014-07-22 00:27:50

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

帖子 has_many upvotes 。列 is_featured 也可以是否有帖子。

我想获得所有精选帖子,按照upvotes(最多到最少)排序,然后是created_at(从最新到最旧)。

以下是我构建查询的方法。 #1和#2工作,但对于#3我不能同时按日期和upvotes排序。

# 1. Get all featured posts
Posts.where(is_featured: true) 

# 2. Get all featured posts, sort by their votes in DESC order. Maybe there is an easier way?
Posts.where(is_featured: true).sort_by{|post| post.upvotes.count}.reverse! 

# 3. Get all featured posts, sort by their votes in DESC order, sort by created_at DESC (doesnt work)
Posts.where(is_featured: true).sort_by{|post| post.upvotes.count}.reverse!.sort_by{|post| post.created_at}.reverse!

什么是正确的查询?

1 个答案:

答案 0 :(得分:0)

我强烈建议您为upvotes实现counter_cache,然后执行:

Posts.where(is_featured: true).order("upvotes_count DESC, created_at DESC")

你upvotes模型应该是这样的

class Upvotes
  belong_to :posts, :counter_cache => true
  ...
end

然后你需要在你的帖子表上使用upvotes_count:整数。