I am having problems searching a money-rails/Monetized attribute using ransack. I am only able to search in cents. I have a model (gig) with a money attribute salary
. I can create this model no problem with:
<%= form.input :salary %>
Which saves the value in a salary_cents
column as expected as in my gig model I have:
monetize :salary_cents
I can then show the salary in the view with:
<%= @gig.salary %>
The problem I am having is with searching this field with ransack. The salary
attribute is null, and the salary_cents
attribute is populated as it should be, but this means I can only search in cents.
For the search I am using:
<%= f.search_field :salary_cents_gteq %>
<%= f.search_field :salary_cents_lteq %>
but to search $30
, I would have to input 3000
. Is there any way of manipulating the inputted data, multiplying by 100, before sending the search request? Are there any easier ways that I am missing?
I have searched this and cannot find any information on searching Money fields with ransack.
Thanks in advance.
Ransack's custom predicates saves the day!
# config/initializers/ransack.rb
Ransack.configure do |config|
config.add_predicate 'gteq_euros',
arel_predicate: 'gteq',
formatter: proc { |v| v * 100 },
validator: proc { |v| v.present? }
config.add_predicate 'lteq_euros',
arel_predicate: 'lteq',
formatter: proc { |v| v * 100 },
validator: proc { |v| v.present? }
end
once you restart your rails application you could ransack by dollars / euros as you wanted:
<%= f.search_field :salary_cents_gteq_euros %>
<%= f.search_field :salary_cents_lteq_euros %>