I am using running a simple find all and paginating with willpaginate, but I’d also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]
http://localhost:3000/posts/?sort=created_at+DESC @posts = Post.paginate :page => params[:page], :order => params[:sort]
But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created_at.
Is this a safe approach to sorting and is there a way to default to created_at?
I’d use a named scope for providing the default order (available since Rails 2.1).
You’d add the scope in your Post model:
Then you can call:
The example above will use the default order from the
named_scope(created_at DESC), but you can also provide a different one:You could use that with Romulo’s suggestion:
If
params[:sort]isn’t found insort_paramsand returnsnilthennamed_scopewill fall back to using the default order.Railscasts has some great info on named_scopes.