Reputation: 21
I'm trying to query all users who had their birthdays 1-2 days ago, who have their birthday today and in 1-2 days from now.
Is it possible to do it in pure rails way, without writing DB specific SQL queries?
User model is simple: user_id, name, dob
There is a good solution here but it's not exactly what I need.
Upvotes: 2
Views: 2069
Reputation: 12514
If you are to find people with birthday today then following will work(PG)
where("date_part('month', users.dob) = ? and date_part('day', users.dob) = ?", Date.current.month, Date.current.day)v
Upvotes: 1
Reputation: 2911
I have one solution. Maybe it's not elegant, but it works for me:
@users=User.all
<% @users.each do |u| %>
<% if u.dob+(Date.today.year-u.dob.year).years >= Date.yesterday && u.dob+(Date.today.year-u.dob.year).years <= Date.tomorrow %>
<%= u.name %>
<%end%>
<%end%>
Upvotes: -1
Reputation: 9003
User.where(:dob => 2.days.ago .. 2.days.from_now)
Will result in a WHERE dob BETWEEN 2_days_ago AND 2_days_from_now
Upvotes: 6