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.
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.
Search Model:
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:
<%= select(@object, :youngest_age, (18..75).to_a) %> to <%= select(@object, :oldest_age, (18..75).to_a) %>
This should do it:
# 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
You'll need to pass back two parameters from your search form to your controller. I'm assuming those will be params[:youngest_age] and params[:oldest_age] for this. I'm also assuming those will be integers (ex: params[:youngest_age] = 18)
youngest_age = params[:youngest_age].years
oldest_age = params[:oldest_age].years
User.where("birthday >= ? AND birthday <= ?", Date.today - youngest_age, Date.today - oldest_age)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With