简体   繁体   English

在Rails中使用Ransack将字符串搜索为整数

[英]Search string as integer with Ransack in Rails

I'm using the Ransack gem to set up a search form for a model. 我正在使用Ransack gem来建立模型的搜索表单。 The model has a field :size which is stored as a string. 该模型具有一个:size字段,该字段存储为字符串。 I'd like to do a comparative search "using lte and gte". 我想做一个比较搜索“使用LTE和GTE”。 How can I cast this field as an integer when searching with ransack? 使用ransack搜索时如何将该字段转换为整数?

Have you tried setting up a simple method that returns the length of the string? 您是否尝试过设置返回字符串长度的简单方法?

def size_length
  size.length
end

Then your ransack could be something like Model.search(:size_length_lteq => comparison) ? 然后,您的洗劫可能类似于Model.search(:size_length_lteq => comparison)吗?

Also what about a custom matcher? 还有自定义匹配器呢? Not sure if this will work, but might be something worth a shot. 不知道这是否行得通,但可能值得一试。

# config/initializers/ransack.rb
Ransack.configure do |config|
  config.add_predicate 'string_lteq',
    arel_predicate: 'lteq',
    formatter: proc { |v| v.length },
    validator: proc { |v| v.present? },
    type: :string
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM