排序列时如何忽略大小写 [英] How to ignore case when sorting a column
问题描述
当我在 ActiveAdmin
中对模型的 name
列进行排序时,得到如下输出: / p>
- 苹果
- 冰柱
- 斑马
- iMacs
- iPhones
其中出现大写和小写字母分别进行排序。我更喜欢以以下方式显示排序的列:
- 苹果
- 冰柱
- iMacs
- iPhones
- Zebras
,不存在不自然的大小写敏感性。我尝试使用该行
列:name,可排序:'my_model.name.downcase'
可以缓解此问题,但这会引发 ActiveRecord :: StatementInvalid
错误。我该如何使用它?
如果将其放在active_admin.rb中:
模块ActiveAdmin
class ResourceController< BaseController
模块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_')
列= $ 2
订单= $ 3
表= active_admin_config.resource_column_names.include?(column)?
active_admin_config.resource_table_name:nil
table_column =(column =〜/\./)吗?列:
[table,active_admin_config.resource_quoted_column_name(column)]。compact.join(。)
chain.reorder(#{'lower'if icase}(#{table_column })#{order})
其他
链#只返回链
结束
结束
结束
结束
结束
然后您可以执行以下操作:
列:name,可排序:'lower_name'
在调用时也可以使用
很显然,如果碰巧要使用名为 lower_anything的列,则可能需要进行调整。
p>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?
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.
这篇关于排序列时如何忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!