简体   繁体   中英

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?

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 %>

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.

def self.age_lteq(age)
  start_birth_year = Date.today.year - age
  where('date_of_birth >= ?', Date.new(start_birth_year))
end

def self.age_gteq(age)
  birth_year = Date.today.year - age
  end_of_birth_year = Date.new(birth_year + 1) - 1
  where('date_of_birth <= ?', end_of_birth_year)
end

private

def self.ransackable_scopes(auth_object = nil)
  %i(age_lteq age_gteq)
end

# In views just do the following (ransack default grouping queries is by AND)
# https://github.com/activerecord-hackery/ransack#grouping-queries-by-or-instead-of-and
<%= f.input :age_lteq %>
<%= f.input :age_gteq %>

@siddick answer is cool, but the logic of lteq acts like gt and gteq acts like lt . I myself is starting out ruby and rails recently. So do tell me if I did anything wrong. :) Thanks!

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:

def self.ransackable_scopes(auth_object = nil)
  %i(age_between)
end

For more info see the docs - https://github.com/activerecord-hackery/ransack#using-scopesclass-methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM