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?
comment_count , : order, , : order = > : comment_count_cache.desc. , Comment.
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-.
, 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 .
Source: https://habr.com/ru/post/1718913/More articles:First row style in WPF Datagrid - c #WPF - GridView.GridViewColumn two rows in a row? - c #Writing .NET for Windows through Linux and Mono - c #Determining relative positions in a layout? - androidIs the Java API a data structure for representing a hierarchy - javaData structure for fast line queries? - c ++How to create own DLL in Visual Studio from C # code? - c ++Scalable coloring application Qt - qtCommunication between AIR (Flex) and C ++ applications - c ++how to avoid All Articles