使用Ransack宝石,我想这样做
>> User.search(first_name_i_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users" WHERE (UPPER("users"."first_name") LIKE UPPER('%Rya%'))
但是此方法尚不可用。
所以我试图弄清楚,还有其他方法可以做到吗我得到了一些有关如何做的信息
//in model
ransacker :ig_case, formatter: proc { |v| v.mb_chars.upcase.to_s } do |parent|
Arel::Nodes::NamedFunction.new('UPPER',[parent.table[:firstname]])
end
//in config/ranrack.rb
Ransack.configure do |config|
config.add_predicate 'ig_case', # Name your predicate
arel_predicate: 'matches',
formatter: proc { |v| "%#{v.to_s.gsub(/([\\|\%|.])/, '\\\\\\1').mb_chars.upcase}%"},
validator: proc { |v| v.present? },
compounds: true,
type: :string
end
// use way
User.search({ firstname_or_lastname_ig_case: "ABC"}).result.to_sql
=> "SELECT `Users`.* FROM `Users` WHERE ((UPPER(`users`.`firstname`) LIKE '%ABC%' OR (`users`.`lastname`) LIKE '%ABC%'))"
几个小时后,我发现每次以模型方式使用时,我只能得到一个大写的字段。
如果我以配置方式选择,但我无法大写所有字段,但是我无法获得这样的sql'UPPER(“用户”。“名字”)'
有什么解决方法吗?我真的非常感谢。
您需要通过执行以下操作来覆盖适配器中的Arel:
module Arel
module Nodes
%w{
IDoesNotMatch
IMatches
}.each do |name|
const_set name, Class.new(Binary)
end
end
module Predications
def i_matches other
Nodes::IMatches.new self, other
end
def i_does_not_match other
Nodes::IDoesNotMatch.new self, other
end
end
module Visitors
class ToSql < Arel::Visitors::Visitor
def visit_Arel_Nodes_IDoesNotMatch o
"UPPER(#{visit o.left}) NOT LIKE UPPER(#{visit o.right})"
end
def visit_Arel_Nodes_IMatches o
"UPPER(#{visit o.left}) LIKE UPPER(#{visit o.right})"
end
end
class Dot < Arel::Visitors::Visitor
alias :visit_Arel_Nodes_IMatches :binary
alias :visit_Arel_Nodes_IDoesNotMatch :binary
end
class DepthFirst < Visitor
unless method_defined?(:visit_Arel_Nodes_InfixOperation)
alias :visit_Arel_Nodes_InfixOperation :binary
alias :visit_Arel_Nodes_IMatches :binary
alias :visit_Arel_Nodes_IDoesNotMatch :binary
end
end
end
end
此外,您需要提供谓词的方法。
这是我的宝石之叉,可以解决您的问题:https://github.com/Kartstig/ransack
我有一个已关闭的PR,因为它可能已经损坏了其他适配器。到目前为止,我的应用程序在运行中表现出色:https://github.com/activerecord-hackery/ransack/pull/405
还请注意,如果您有任何索引列,则它们将被忽略,因为您使用的是UPPER。
现在书包中已经有_i_cont谓词,您可以使用它:)