Search code examples
ruby-on-railsransack

gem Ransack custom search for only Year instead of full date


I have a Rails 5.1 application and a Ransack search form with a dropdownlist containing some database columns. One of the column is finish_date and has values in format eg "2007-12-31". In the input field I have to type exactly the full date to get a match but I want to change the behaviour that it accepts only the year as input value.

How can I pass in a custom predicate that transforms the input value from full date eg. 2007-12-31 to only year?

What I'm looking for is a Ransack equivalent for the sql query:

SELECT *
 FROM imagecapturing
 WHERE YEAR(finish_date) = 2007

My Ransack form:

<%= search_form_for @search do |f| %>
  <%= f.grouping_fields(f.object.new_grouping) do |g| %>
    <%= g.condition_fields(g.object.new_condition) do |c| %>
      <%= c.predicate_select only: %i(cont not_eq eq) %>
      <%= c.value_fields do |v| %>
        <%= v.text_field :value %>
      <% end %>
    <% end %>
  <% end %>
  <%= f.submit "filter" %>
<% end %>

in my controller:

  @search = Imagecapturing.ransack params[:q]
  @imagecapturings = @search.result.page params[:page]

Solution

  • Use Ransacker:

    You can write something like this in your model:

      ransacker :custom_years do |args|
        query = <<-SQL
          Year(finish_date)
        SQL
        Arel.sql(query)
      end
    

    See also using Ransacker on Ransack Wiki