Mongoid命名范围比较同一文档中的两个时间字段 [英] Mongoid named scope comparing two time fields in the same document

查看:68
本文介绍了Mongoid命名范围比较同一文档中的两个时间字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Mongoid中创建一个命名作用域,以比较同一文档中的两个时间"字段.如

I need to create a named scope in Mongoid that compares two Time fields within the same document. Such as

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

这显然不起作用,因为它将:checked_at视为符号,而不是实际字段.关于如何做到这一点有什么建议吗?

This obviously won't work as it treats :checked_at as a symbol, not the actual field. Any suggestions on how this can be done?

更新1

在这里,我声明了这个作用域,并去除了很多额外的代码.

Here is my model where I have this scope declared, with a lot of extra code stripped out.

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

这给了我以下错误:

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

推荐答案

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

As far as I know, mongodb doesn't support queries against dynamic values. But you could use a javascript function:

scope :unresolved, :where => 'this.updated_at >= this.checked_at'

为加快速度,您可以添加一个属性,例如"is_unresolved",该属性在匹配此条件(并为其索引)时将在更新时设置为true.

To speed this up you could add an attribute like "is_unresolved" which will be set to true on update when this condition is matched ( and index that ).

这篇关于Mongoid命名范围比较同一文档中的两个时间字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆