我想使用 ransack 为页面构建高级搜索功能Users
。
我有一个小方法可以从出生日期计算年龄:
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
这适用于正常显示(as in age(@user.date_of_birth)
)
但是当使用 search_form_for 时我不能做同样的事情:
<%= 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 %>
我的问题是:如何在搜索中使用年龄而不是出生日期?
添加如下所示的范围来查找给定年龄的日期。
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
}
对于掠夺语法:
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 %>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)