Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ransack: using age instead of date of birth

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?

like image 733
TimmyOnRails Avatar asked Feb 18 '23 02:02

TimmyOnRails


1 Answers

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 %>
like image 159
siddick Avatar answered Feb 20 '23 17:02

siddick