Search code examples
ruby-on-railsrubypostgresqlransack

How can I search for dates using Ransack in rails


I'm using Ransack in rails. I'm completely open to pulling this out and using something different that might play nicer with dates. I just used ransack because I'm somewhat familiar with it. Db is Postgres.

I have an orders model with a 'check_out_date' column.

I simply want to search for orders with a specific date.

Here's my form:

    <%= search_form_for @q do |f| %>
    <%= f.date_field :check_out_date_cont  %>
    <%= f.submit 'search', class: "btn btn-warning" %>
    <% end %>

Here's my controller:

  def index
    @q = Rental.ransack(params[:q])
    @rentals = @q.result(distinct: true)
  end

I've researched the problem, and I keep seeing people adding a ransacker in the model like what I have done here:

  ransacker :check_out_date, type: :date do
    Arel.sql('date(check_out_date)')
  end

I will say this. I have ransack working otherwise. I can easily throw in a 'title' search field for example and it works perfectly. However, when I search by date, here's what I'm still getting:

PG::UndefinedFunction: ERROR:  operator does not exist: date ~~* unknown
LINE 1: ...".* FROM "orders" WHERE "orders"."check_out_date" ILIKE '202...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

anyone run into this issue with a simple solution?


Solution

  • Your query param is called check_out_date_cont. _cont at the end signals to ransack that you want all records for which check_out_date column contains a given string - which is why it is using ILIKE operator which simply does not work for dates.

    You need to change it to check_out_date_eq for this to work.

    Reference: https://github.com/activerecord-hackery/ransack#search-matchers