How to set defaults for ransack sorting?
Asked Answered
S

2

22

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!

Schrecklichkeit answered 13/11, 2012 at 22:22 Comment(0)
A
50

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.

Arachnid answered 12/2, 2013 at 7:56 Comment(0)
T
7

You can also set multiple default sorts by defining an array:

@search = Post.ransack(params[:q])  
@search.sorts = ['name asc', 'created_at desc'] if @search.sorts.empty?
@posts = @search.result.paginate(page: params[:page], per_page: 20)

https://github.com/activerecord-hackery/ransack/wiki/Sorting-in-the-Controller

The answered 8/1, 2016 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.