A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Wednesday, August 7, 2013

Default Sort Order in Ransack Rails Gem

Ernie Miller's Ransack gem is a great way to handle searching and sorting of data in a Rails 3 application. It is the successor to his meta_search gem. There is a railscast episode on ransack.

But while Ransack offers benefits over meta_search, it is lacking in documentation which is a shame.

The problem I ran into was how to set a default sort order for records in the controller, before one had been set in the view.

Here is how you specify this:
      @search = Post.search(params[:q])

      @search.sorts = 'name asc' if @search.sorts.empty?

      @posts = @search.result.paginate(:page => params[:page],
                                 :per_page => 20)


The other problem that I am still dealing with is that Ransack does not appear to let you use scopes from your model in the search form. meta_search did allow this. That turns out to be a big issue in a current project to port an older application into Rails 3.

No comments:

Archive of Tips