Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 要按Datamapper中的关联记录计数排序吗_Ruby_Sorting_Associations_Datamapper - Fatal编程技术网

Ruby 要按Datamapper中的关联记录计数排序吗

Ruby 要按Datamapper中的关联记录计数排序吗,ruby,sorting,associations,datamapper,Ruby,Sorting,Associations,Datamapper,假设我有以下DataMapper资源: class Post include DataMapper::Resource has n, :comments ... end class Comment include DataMapper::Resource belongs_to :post ... end 要获得有序的帖子列表,我知道您可以执行以下操作: @posts = Posts.all(:order => :date.desc) 但假设我想

假设我有以下DataMapper资源:

class Post
  include DataMapper::Resource 

  has n, :comments
  ...

end  

class Comment
  include DataMapper::Resource 

  belongs_to :post
  ...

end
要获得有序的帖子列表,我知道您可以执行以下操作:

@posts = Posts.all(:order => :date.desc)

但假设我想显示所有按评论数量降序排列的帖子。我该怎么做?

我相信您要生成的SQL是:

SELECT posts.*, COUNT(comments.id) AS comments_count FROM posts
JOIN comments ON posts.id = comments.post_id
GROUP BY posts.id ORDER BY comments_count DESC

据我所知,这不是可以用Query类编程实现的。出于性能原因,一个很好的方法是缓存帖子的comment\u count值,这将为您提供一个用于:order的属性,可能类似于:order=>:comment\u count\u cache.desc。通过为注释模型添加一个创建后钩子,可以很容易地进行设置。

您也可以使用sort\u by,它调用一个单独的查询:

@post = Post.all(:order => :date.desc).sort_by { |post| -post.comments.count }
如果要更改顺序,可以去掉减号:

@post = Post.all(:order => :date.desc).sort_by { |post| post.comments.count }
这在语法上很好,但正如adamaig指出的那样,它的性能可能比缓存数据库中的注释数还要差,因为您添加了一个额外的SQL查询