user804968
user804968

Reputation: 181

How can I order records from newest to oldest?

This my code:

@statuses = []
current_user.friends.each do |f|
  @statuses = @statuses + f.statuses 
end
@sorted_statuses = @statuses.sort_by { |obj| obj.created_at }

I'm taking all my friends statuses from the database and puting them on the wall. I'm trying to show them from the new (at the top) to the old (at the bottom), buy right now its vice versa. Please let me know how to change it.

Upvotes: 1

Views: 2367

Answers (2)

KARASZI István
KARASZI István

Reputation: 31467

You can even define the default order in your model with default_scope

class Person < ActiveRecord::Base
  default_scope order('last_name, first_name')
end

Upvotes: 0

DGM
DGM

Reputation: 26979

No need to pre-declare the array, or post process on another line. the ordering can be done via database. The ruby way is:

@statuses = current_user.friends.order('created_at DESC').collect {|f| f.statuses}

Upvotes: 8

Related Questions