简体   繁体   中英

Search string as integer with Ransack in Rails

I'm using the Ransack gem to set up a search form for a model. The model has a field :size which is stored as a string. I'd like to do a comparative search "using lte and gte". How can I cast this field as an integer when searching with 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) ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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