【问题标题】:How can I fix this Rails AR query to get records that are at least 5 minutes old?如何修复此 Rails AR 查询以获取至少 5 分钟前的记录?
【发布时间】:2023-04-02 19:13:01
【问题描述】:

编写返回至少 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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord time


    【解决方案1】:
    Note.where('created_at <= ?', 5.minutes.ago).where(:private_note => false).order('date DESC')
    

    【讨论】:

      【解决方案2】:
      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) }
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-30
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多