写一个返回至少5分钟记录的Rails查询的最佳方法是什么?我使用的是Rails 3.0.1,Ruby 1.9.2和PostgreSQL。目前我有这个:
Note.order('date DESC').where('private_note = ? AND (?-created_at) > 300',false, Time.now.utc)
会出现这些错误:
Note Load (0.7ms) SELECT "notes".* FROM "notes" 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'
示例created_at值为2011-09-28 01:00:01 UTC
答案 0 :(得分:7)
Note.where('created_at <= ?', 5.minutes.ago).where(:private_note => false).order('date DESC')
答案 1 :(得分:0)
Note.where('created_at < ?', Time.now.utc - 5.minutes)
要记住像Time.now这样的事情的一件事是,如果你最终将它放入一个范围,使用lambda而不是将它直接传递给范围,否则Time.now将是常量。
scope :older_than_5_minutes, lambda { order(...).where('...', Time.now.utc - 5.minutes) }