Tim*_*ils 4 ruby ruby-on-rails ransack
我想使用 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
Run Code Online (Sandbox Code Playgroud)
这适用于正常显示 ( 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 %>
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何在搜索中使用年龄而不是出生日期?
添加如下 Scope 以查找给定年龄的日期。
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
}
Run Code Online (Sandbox Code Playgroud)
对于 ransacke 语法:
ransacker :age, :formatter => proc {|v| Date.today - v.to_i.year} do |parent|
parent.table[:date_of_birth]
end
Run Code Online (Sandbox Code Playgroud)
在视图中
<%= f.text_field :age_gteq %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1902 次 |
| 最近记录: |