Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

How to get data of last 24 hours on top in rails

There is a model post . Post are created by either PM or User. I want to get all posts in which the posts created by PM in last 24 hours come on top.

I try

posts.sort_by{|t| -t["role_id"] }

But by this PM all posts on top. I want PM posts of only last 24 hours on top.

Upvotes: 3

Views: 3630

Answers (2)

jpgeek
jpgeek

Reputation: 5291

To confirm your question, you want ALL records and the sort to be:

  1. Records created by pm && within last 24 hours (internally sorted by something else)
  2. followed by all other records sorted by something else.

I would create a synthetic boolean sort field like this:

time = 24.hours.ago.strftime("%Y-%m-%d %M:%S")
Post.order("(created_at < '#{time}' && cont_term = 24) ASC")

It will resolve to 0 or 1 so you can sort by this field first and add additional order() clauses to sort within those groups.

Upvotes: 1

Murad Yusufov
Murad Yusufov

Reputation: 552

Try this: Post.where('created_at > ?', 24.hours.ago).order(role_id: :asc)

Upvotes: 7

Related Questions