[Solved] Rails: Find record by created_at beginning_of_week


Because created_at is a DateTime object which includes both a Date and Time value, then your

Message.find_by(created_at: Date.today.beginning_of_week)
# Message Load (6.2ms)  SELECT  "messages".* FROM "messages" WHERE "messages"."created_at" = $1 LIMIT $2  [["created_at", "2018-01-29"], ["LIMIT", 1]]

… will try to find a record at exactly 2018-01-29 00:00:00 which is a Message record that is exactly created at midnight, instead of 2018-01-29 that you might have expected. You do not want that and instead want ANY record that is created in that day (as far as I understood your question). So, you can try the following instead.

date_beginning_this_week = Date.today.beginning_of_week
Message.where(created_at: date_beginning_this_week..(date_beginning_this_week + 1.day))
# Message Load (0.2ms)  SELECT  "messages".* FROM "messages" WHERE ("messages"."created_at" BETWEEN $1 AND $2) LIMIT $3  [["created_at", "2018-01-29"], ["created_at", "2018-01-30"], ["LIMIT", 11]]

0

solved Rails: Find record by created_at beginning_of_week