views:

38

answers:

3
@posts = Category.find(params[:id]).posts

How can I order the results with column from the posts table? For example on the posts.created_at column?

+1  A: 

You can do this:

@posts = Category.find(params[:id]).posts.all(:order => "created_at")

not sure if there are better ways of doing it... hope that helps =)

Staelen
+1  A: 
@posts = Category.find(params[:id]).posts.all(:order => "created_at")

You can also add to this other things such as

@posts = Category.find(params[:id]).posts.all(:order => "created_at", :limit => 10)

or

@posts = Category.find(params[:id]).posts.all(:order => "created_at DESC")
iano
A: 

Another very simple solution is to simply specify the order on the association itself.

class Post < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :posts, :order => "created_at"
end

Any posts fetched via the association will already be sorted. This will let you keep the ordering details in the model itself and the SQL-ish syntax out of the controller.

@posts = Category.find(params[:id]).posts

Will give you back your records in "created_at" order.

guitarzan