I would like to use ransack to build an advanced search function for a page with Users
.
I have a small method to calculate age from date of birth:
def age(dob)
now = Time.now.utc.to_date
now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end
That works on normal display (as in age(@user.date_of_birth)
)
But when using search_form_for I cannot do the same:
<%= search_form_for @search, url: search_users_path, method: :post do |f| %>
<div class="field">
<%= f.label :date_of_birth_gteq, "Age between" %>
<%= f.text_field :date_of_birth_gteq %>
<%= f.label :date_of_birth_gteq, "and" %>
<%= f.text_field :date_of_birth_lteq %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
My question is: how can I use age in my search instead of date of birth?
Just an update on @siddick answer (which works perfectly). You now need to white list scopes that ransack offers. In the case of the answer from @siddick you need to do this:
For more info see the docs - https://github.com/activerecord-hackery/ransack#using-scopesclass-methods
Add a Scope like below to find the date for the given age.
For ransacke syntax:
In view
I do not know ransacker personally and tried to use ransacker but couldn't find any thing that could check the predicate passed in. Hence I believe it's better to use scopes to do it.
@siddick answer is cool, but the logic of
lteq
acts likegt
andgteq
acts likelt
. I myself is starting out ruby and rails recently. So do tell me if I did anything wrong. :) Thanks!