Want to sort by record association records in Datamapper

Suppose I have the following DataMapper resources:

class Post
  include DataMapper::Resource 

  has n, :comments
  ...

end  

class Comment
  include DataMapper::Resource 

  belongs_to :post
  ...

end

To get an ordered list of messages, I know what you can do:

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

But I’ll say that I want to display all orders in descending order, how many comments they have. How can I do it?

+3
source share
3 answers

comment_count , : order, , : order = > : comment_count_cache.desc. , Comment.

+1

sort_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, , , , db, SQL-.

+2

, 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. SQL .

+1

Source: https://habr.com/ru/post/1718913/


All Articles