@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?
@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?
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 =)
@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")
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.