yellowreign
yellowreign

Reputation: 3638

Rails: Reordering an ActiveRecord result set

I want to retrieve the last five Articles by review date, but I want to display them in chronological order (ascending order). How do I do this?

# controller
@recent_articles = Article.where("reviewed = ?", true).order("review_date DESC").limit(5)

# view
<% @recent_articles.each do |ra| %>
  # articles sorted by review_date in ascending order
<% end %>

I tried doing this in the controller, but it retrieved the five oldest review_dates instead (i.e. it just retrieved the records by ASC order instead of reordering the array already retrieved):

@recent_articles = Article.where("reviewed = ?", true).order("review_date DESC").limit(5)
@recent_articles = @recent_articles.reorder("review_date ASC")   

Upvotes: 1

Views: 1497

Answers (2)

user419017
user419017

Reputation:

I'd suggest you create a reviewed and recent scopes in your model. This will allow nicely chain-able scopes in your controllers:

# article.rb

scope :reviewed, lambda { where("reviewed = ?", true) }
scope :recent,   lambda { |n| order("review_date").last(n) }

# in your controller..

@recent_articles = Article.reviewed.recent(5)

Notice I'm using last(n), not limit. There is no point in ordering by review_date desc just to get the latest articles by review date, then reorder them because the query was wrong. Unless you're using review_date desc for another reason, use last instead.

Upvotes: 3

gregates
gregates

Reputation: 6724

So you want the articles from the DESC query but in the reverse order that they come in from the database?

@recent_articles.reverse!

Upvotes: 5

Related Questions