How to set defaults for ransack sorting?

牧云@^-^@ 提交于 2019-12-14 04:16:38

问题


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:

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

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

Thanks in advance as always!

Best Regards!


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13369909/how-to-set-defaults-for-ransack-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!