Mongoid命名范围比较同一文档中的两个时间字段

Jey*_*ran 5 ruby-on-rails mongodb mongoid

我需要在Mongoid中创建一个命名范围,用于比较同一文档中的两个时间字段.如

scope :foo, :where => {:updated_at.gt => :checked_at}

这显然不会起作用,因为它被视为:checked_at一个符号,而不是实际的领域.有关如何做到这一点的任何建议?

更新1

这是我的模型,我声明了这个范围,删除了许多额外的代码.

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  include Mongoid::Timestamps

  field :checked_at, :type => Time

  scope :unresolved, :where => { :updated_at.gt => self.checked_at }
end
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

'<class:User>': undefined method 'checked_at' for User:Class (NoMethodError)

Baj*_*aju 7

据我所知,mongodb不支持对动态值的查询.但你可以使用javascript函数:

scope :unresolved, :where => 'this.updated_at >= this.checked_at'
Run Code Online (Sandbox Code Playgroud)

为了加快这一速度,你可以添加一个像"is_unresolved"这样的属性,当这个条件匹配时(和索引那个),它将在更新时设置为true.