Search code examples
ruby-on-railsrubygemsransackmoney-rails

Ransack search for price with Money-rails


I'm using Ransack to add a search function to my rails app and I'm also using Money-rails gem to handle price and currency.

I want to enter a price in Dollars in the Ransack search field and then it converts it to cents in order to find it in the relevant table.

So basically the problem is how to convert the input form Dollars to cents before submitting the search with Ransack.

Search form:

<div class="form-group">
    <%= f.label :price_cents_gteq, "Price between" %>
    <%= f.text_field :price_cents_gteq %>
    <%= f.label :price_cents_lteq, "And" %>
    <%= f.text_field :price_cents_lteq %>
</div>

Thanks a lot in advance!


Solution

  • Custom predicate can solve the problem.

    You can use formatter proc to convert dollar to cents. Problems can arise when you will display ransack object value of price.

    Update #1

    Or even better, you can solve it with ransacker class method.

    Update #2

    Here is the raw solution with model and ransaker method:

    # model
    ransacker :price_money, type: :integer, formatter: proc { |dollars| dollars * 100 } do |p|
      p.table[:price_cents]
    end
    
    # form in view
    <%= f.number_field :price_money_gteq %>
    <%= f.number_field :price_money_lteq %>