idjuradj
idjuradj

Reputation: 1465

Order articles by date and by votes using acts_as_votable gem

I'm trying to create a rating system in my app. I decided to use acs_as_votable gem, as it seems to be a powerful and popular gem that offers voting functionality.

I want to make my articles votable, and that works.

However, I would like to sort articles based on publishing date, and then sort the articles published on the same day by number of upvotes.

I think the question is clear, but let me illustrate by example.

Let's say Article , Article and Article 3 are published today and they have 5, 3, 10 upvotes, respectively.

Article 4, article 5 and article 6 are articles posted yesterday and they have 1,2 and 3 upvotes respectively.

Sorted articles should look like

Article 3 (10 upvotes)
Article 1 (5 upvotes)
Article 2 (3 upvotes)
Article 6 (3 upvotes)
Article 5 (2 upvotes)
Article 4 (1 upvote)

Ideally, I would like to extract the date before all articles posted on the same day (something like on producthunt) so it would loo like this, but this is optional.

**9/22/2015**
Article 3 (10 upvotes)
Article 1 (5 upvotes)
Article 2 (3 upvotes)
**9/21/2015**
Article 6 (3 upvotes)
Article 5 (2 upvotes)
Article 4 (1 upvote)

Simple sorting by upvotes was solved here: acts_as_votable ordering by upvotes

But how do I sort by two criteria: date and upvote?

Upvotes: 1

Views: 630

Answers (1)

Bryan Dimas
Bryan Dimas

Reputation: 1452

After you implement caching on acts_as_votable as documented on the posting you referenced, you should be able to just do something like:

Article.order(cached_votes_total: :desc, published_at: :desc)

Rails will do the trick for you. I found this posting helpful: Ruby on Rails: how do I sort with two columns using ActiveRecord?

Upvotes: 2

Related Questions