ruby-on-rails – Ransack:使用年龄而不是出生日期
发布时间:2020-12-17 02:44:40 所属栏目:百科 来源:网络整理
导读:我想使用ransack为用户构建一个高级搜索功能. 我有一个小方法来计算从出生日期开始的年龄: 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 这适用于正
我想使用ransack为用户构建一个高级搜索功能.
我有一个小方法来计算从出生日期开始的年龄: 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 这适用于正常显示(如年龄(@ 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 } 对于ransacke语法: ransacker :age,:formatter => proc {|v| Date.today - v.to_i.year} do |parent| parent.table[:date_of_birth] end 在视野中 <%= f.text_field :age_gteq %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |