Search for records created 10 days ago

My initial thought:

user.humans.where("created_at = ?", 10.days.ago)

      

Although it seems to be looking for a record that was created 10 days ago at the time the statement is called. I want to collect the records created on this day, regardless of their time.

Does anyone know of a convenient way to do this? Let me know if I need to clarify.

Thank.

+3


source to share


2 answers


You probably want to use a range here, since I'm assuming it's a datetime column.

User.humans.where("? <= created_at AND created_at <= ?", 10.days.ago.beginning_of_day, 10.days.ago.end_of_day)

      



You will also want to make sure that you set the timezone of your Rails application so that you are clear about what time period you think is the 10th day.

+6


source


Whichever DBMS you are using will have a method to convert date and time to date. Then you have to compare this to the date in ruby. For example, if your DBMS is MySQL, you can say

user.humans.where("date(created_at) = ?", 10.days.ago.to_date)

      



If you are not using MySQL, you should be able to convert datetime to date in your DBMS of choice.

+1


source







All Articles