How to configure Ransack Rails Gem to add NULLS LAST to sort

懵懂的女人 提交于 2019-12-23 12:19:30

问题


I would like Ransack to always add NULLS LAST which will put nulls last for the sort column.

Any way to do this?

I opened a github issue on this one: https://github.com/activerecord-hackery/ransack/issues/443


回答1:


The answer is found in the thread linked in the question above. Writing it here so its easier to find. Apparently you need to build the order string again and add Null Last to it.

This solved it for me (works on all columns):

@q.result.except(:order).order("#{@q.sorts.first.name} #{@q.sorts.first.dir} NULLS LAST")

However you need to exclude it when you don't have any sort parametre, so this is my final solution:

@q = Project.ransack(params[:q])
@fields = current_user.settings.default_project_fields
if @q.sorts.present?
  @result = @q.result.except(:order).order("#{@q.sorts.first.name} #{@q.sorts.first.dir} NULLS LAST")
else
  @result = @q.result
end


来源:https://stackoverflow.com/questions/26321628/how-to-configure-ransack-rails-gem-to-add-nulls-last-to-sort

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