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?
Add a Scope like below to find the date for the given age.
scope :age_between, lambda{|from_age, to_age|
if from_age.present? and to_age.present?
where( :date_of_birth => (Date.today - to_age.to_i.year)..(Date.today - from_age.to_i.year) )
end
}
For ransacke syntax:
ransacker :age, :formatter => proc {|v| Date.today - v.to_i.year} do |parent|
parent.table[:date_of_birth]
end
In view
<%= f.text_field :age_gteq %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With