How to ignore case when sorting a column

扶醉桌前 提交于 2019-12-23 04:54:09

问题


When I sort the name column of a model in ActiveAdmin, I get output such as the following:

  • Apples
  • Icicles
  • Zebras
  • iMacs
  • iPhones

where the uppercase and lowercase letters appear to be sorted separately. I prefer to display sorted columns in the following manner:

  • Apples
  • Icicles
  • iMacs
  • iPhones
  • Zebras

with no unnatural case sensitivity. I tried using the line

column :name, sortable: 'my_model.name.downcase'

to mitigate the issue, but this throws an ActiveRecord::StatementInvalid error. How can I get this to work?


回答1:


If you put this in your active_admin.rb:

module ActiveAdmin

  class ResourceController < BaseController

    module DataAccess
      def apply_sorting(chain)
        params[:order] ||= active_admin_config.sort_order
        if params[:order] && params[:order] =~ /^(lower_)?([\w\_\.]+)_(desc|asc)$/
          icase = params[:order].to_s.starts_with?('lower_')
          column = $2
          order  = $3
          table  = active_admin_config.resource_column_names.include?(column) ?
            active_admin_config.resource_table_name : nil
          table_column = (column =~ /\./) ? column :
          [table,active_admin_config.resource_quoted_column_name(column)].compact.join(".")

          chain.reorder("#{'lower' if icase}(#{table_column}) #{order}")
        else
          chain # just return the chain
        end
      end
    end
  end
end

Then you can do:

column :name, sortable: 'lower_name'

This will also work if calling the column method with a block.

Obviously if you happen to have a column that you want to do this with that's named "lower_anything" you may need to tweak.



来源:https://stackoverflow.com/questions/20251099/how-to-ignore-case-when-sorting-a-column

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