How to set defaults for ransack sorting?

jlstr picture jlstr · Nov 13, 2012 · Viewed 8.4k times · Source

To put simply enough, I'd just like to know if there's a way to set defaults for the sorting functionality using the Ransack gem? ie.

Currently, I have the following when the page loads:

empty_ransack

But instead, I'd like to have the following defaults when the page loads:

ransack with defaults

Is it possible to do this via proper configuration of the Ransack Gem?

Thanks in advance as always!

Best Regards!

Answer

Christopher Creutzig picture Christopher Creutzig · Feb 12, 2013

This works for me:

@search = Change.search(params[:q])
@search.sorts = 'updated_at desc' if @search.sorts.empty?

Note: I had some head scratching at first, when I had desc in uppercase – that just doesn't work.