[Rails] How to sort the data in the parent table by the number of retrieved data in the child table

Asked 1 years ago, Updated 1 years ago, 117 views

I'm worried about how to change the order in which Rails outputs from activerecord.


as shown below Parent Table - post
The child table-like is associated.

#app/models/post.rb
class Post
 has_many —like
end

# app/models/like.rb
class Like
 belongs_to —Post
end

What I want to do is sort the Posts according to the number of likes made yesterday.
I don't know how to do it.

Simply rearranging the posts in order of the number of likes was as follows.

Post.joins(:likes).group('posts.id') .order('COUNT(likes.id)DESC') .limit(100)

How can I rearrange this with the likes made yesterday?

Thank you for your cooperation.

ruby-on-rails rails-activerecord

2022-09-30 20:36

1 Answers

If you want to sort by the likes made yesterday, how about this code?

Post.
  joins(:likes).
  group('posts.id').
  order("SUM(CASE WHEN likes.created_at BETWEEN'2015-04-07 00:00'AND'2015-04-07 23:59:59'THEN1ELSE0END)DESC").
  limit(100)

Since it's not a where clause, you probably need to embed the date string directly as a string (or use the system date on DB and DB functions to create "Yesterday's Start and End Date")
If you get errors or don't get the results you thought you would, please tell me which RDBMS you are using in the app.

The code above passes the date and time as a string, but you cannot specify the intended time period unless you consider the time zone properly.
Also, you cannot write a uniform answer because the time zone depends on the Rails, OS, and DB settings.
Please refer to this article for more information.


2022-09-30 20:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.