根据出生日期搜索用户年龄 [英] search for users age based on date of birth
问题描述
我无法理解如何根据用户的出生日期对其年龄进行范围搜索.我的数据库仅存储用户 dob.我希望访问者使用高级搜索表单并执行年龄搜索,例如18-23"、28-36"等.
I am having trouble understanding how to perform a range search of a users age based on their date of birth. My DB stores the user dob only. I want for visitors to use the advanced search form and perform age searches such as '18-23', '28-36', etc.
我尝试了一些东西,但似乎都不起作用.我为用户模型添加了范围,def min &最大年龄,以及另一种没有成功的解决方案.也许我得到了一些正确的代码,但没有执行其他部分.我不知道.如果有人能指导我正确的方向,那就太好了,这样我就可以学习了.
I have tried a few things but none seem to work. I added scope to User model, def min & max age, and one other solution that did not pan out. Maybe I am getting some of the code right but not executing the other part. I am not sure. If someone can guide me the right direction that would be great so I can learn this.
当我根据选定的年龄执行搜索时,它会返回所有用户.
When I perform a search based on selected age it returns all users.
搜索模型:
attr_accessible :age, :children, :ethnicity, :career, :gender, :religion, :zip_code, :birthday, :max_age, :min_age, :youngest_age, :oldest_age
def users
@users ||= find_users
end
private
def find_users
users = User.order(:id)
users = users.where(gender: gender) if gender.present?
users = users.where(zip_code: zip_code) if zip_code.present?
users = users.where(children: children) if children.present?
users = users.where(religion: religion) if religion.present?
users = users.where(ethnicity: ethnicity) if ethnicity.present?
users = users.where("birthday >= ? AND birthday <= ?", 80.years.ago + 1.day, 18.years.ago)
users
end
end
Search_Form:
Search_Form:
<%= select(@object, :youngest_age, (18..75).to_a) %> to <%= select(@object, :oldest_age, (18..75).to_a) %>
推荐答案
应该这样做:
# view
<%= select @object, :min_age, (18..75).to_a %>
to
<%= select @object, :max_age, (18..75).to_a %>
# controller
def show
@search = Search.find(params[:id])
@users = @search.users
end
# Search model
def find_users
users = User.order(:id)
users = users.where(gender: gender) if gender.present?
users = users.where(zip_code: zip_code) if zip_code.present?
users = users.where(children: children) if children.present?
users = users.where(religion: religion) if religion.present?
users = users.where(ethnicity: ethnicity) if ethnicity.present?
if min_age.present? && max_age.present?
min = [ min_age, max_age ].min
max = [ min_age, max_age ].max
min_date = Date.today - min.years
max_date = Date.today - max.years
users = users.where("birthday BETWEEN ? AND ?", max_date, min_date)
end
users
end
这篇关于根据出生日期搜索用户年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!