Ransack:使用年龄而不是出生日期 [英] Ransack: using age instead of date of birth
本文介绍了Ransack:使用年龄而不是出生日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 ransack 为具有 Users
的页面构建高级搜索功能.我有一个从出生日期计算年龄的小方法:
def age(dob)现在 = Time.now.utc.to_datenow.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)结尾
这适用于正常显示(如年龄(@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, 年龄之间"%><%= f.text_field :date_of_birth_gteq %><%= f.label :date_of_birth_gteq, "and" %><%= f.text_field :date_of_birth_lteq %>
<div class="actions"><%= f.submit "Search" %></div><%结束%>
我的问题是:如何在搜索中使用年龄而不是出生日期?
解决方案
添加如下所示的 Scope 以查找给定年龄的日期.
scope :age_between, lambda{|from_age, to_age|如果 from_age.present?和to_age.present?where(:date_of_birth => (Date.today - to_age.to_i.year)..(Date.today - from_age.to_i.year) )结尾}
对于ransacke语法:
ransacker :age, :formatter =>过程{|v|Date.today - v.to_i.year} do |parent|parent.table[:date_of_birth]结尾
在视图中
<%= f.text_field :age_gteq %>
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 %>
这篇关于Ransack:使用年龄而不是出生日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文