简体   繁体   中英

Rails where doesn't work with time comparison

There is something weird with this query, which I can't solve

I have a post model which has_many comments. I want to fetch the comments from the last 24 hours

p=Post.first

 p.comments.where("(:t - comments.created_at) <= :d", t: Time.now, d: 1.day)
  Comment Load (1.0ms)  SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = 76 AND "comments"."commentable_type" = 'Post' AND (('2013-03-07 06:08:09.045488' - comments.created_at) <= 86400) ORDER BY created_at DESC

However, this doesn't give me anything, even though p.comments is

[#<Comment id: 132, title: "", comment: "comment", commentable_id: 76, commentable_type: "Post", user_id: 1, created_at: "2013-03-07 05:43:37", updated_at: "2013-03-07 05:43:37">]

Why is that?

比较日期可能比用created_at减去当前日期更有意义。

p.comments.where("comments.created_at > ?", 1.day.ago)
p.comments.where(:created_at => 1.day.ago..Time.now)

This will helps you. It will fetch all the comments between these times.

尝试这个,

 p.comments.where("(created_at >= :t1) and (created_at < :t2)" , t1: (Time.now - 1.day).beginning_of_day, t2: (Time.now - 1.day).end_of_day)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM