开发者

How can I fix this Rails AR query to get records that are at least 5 minutes old?

What is the best way to write a Rails query that returns records that are at least 5 minutes old? I am using Rails 3.0.1, Ruby 1.9.2 and PostgreSQL. At the moment I have this:

Note.order('date DESC').where('private_note = ? AND (?-created_at) > 300',false, Time.now.utc)

which gets these errors:

Note Load (0.7ms)  SELECT "notes".* FROM "not开发者_开发技巧es" WHERE (private_note = 'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORDER BY date DESC
PGError: ERROR:  operator does not exist: interval > integer
LINE 1: ...'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORD...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT     "notes".* FROM       "notes"  WHERE     (private_note = 'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORDER BY  date DESC
Completed   in 214ms

ActiveRecord::StatementInvalid (PGError: ERROR:  operator does not exist: interval > integer
LINE 1: ...'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORD...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT     "notes".* FROM       "notes"  WHERE     (private_note = 'f' AND ('2011-09-28 01:07:30.094475'-created_at) > 300) ORDER BY  date DESC):
  app/controllers/notes_controller.rb:17:in `public_stream_get_notes'

A sample created_at value is 2011-09-28 01:00:01 UTC


Note.where('created_at <= ?', 5.minutes.ago).where(:private_note => false).order('date DESC')


Note.where('created_at < ?', Time.now.utc - 5.minutes)

One thing to keep in mind with things like Time.now is that if you end up putting that into a scope, use a lambda instead of passing it directrly to the scope, otherwise Time.now will be constant.

scope :older_than_5_minutes, lambda { order(...).where('...', Time.now.utc - 5.minutes) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜