Ruby on rails Mongoid命名范围比较同一文档中的两个时间字段
我需要在Mongoid中创建一个命名范围,用于比较同一文档中的两个时间字段。比如Ruby on rails Mongoid命名范围比较同一文档中的两个时间字段,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,我需要在Mongoid中创建一个命名范围,用于比较同一文档中的两个时间字段。比如 scope:foo,:where=>{:updated\u at.gt=>:checked\u at} 这显然不起作用,因为它将:checked\u at视为一个符号,而不是实际字段。有没有关于如何做到这一点的建议 更新1 这是我的模型,我在其中声明了这个范围,并去掉了很多额外的代码 class User include Mongoid::Document include Mongoid::Paranoia
scope:foo,:where=>{:updated\u at.gt=>:checked\u at}
这显然不起作用,因为它将:checked\u 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
这给了我以下错误:
“”:未定义的方法已选中用户:类(NoMethodError)
例如,这将起作用:
scope :foo, where(:start_date.lte=>Date.today.midnight)
据我所知,mongodb不支持对动态值的查询。 但您可以使用javascript函数:
scope :unresolved, :where => 'this.updated_at >= this.checked_at'
为了加快速度,您可以添加一个属性,如“is_unresolved”,当此条件匹配时,该属性将在更新时设置为true(并对其进行索引)。不确定您是否喜欢此方法,它不是最好的,但应该可以工作
class User
include Mongoid::Document
include Mongoid::Paranoia
include Mongoid::Timestamps
field :checked_at, :type => Time
scope :unresolved, lambda{ |user| where(:updated_at.gt => user.checked_at) }
end
您使用User.unresolved(my\u User\u对象)调用它
现在看来,在重读你的文章后,这可能不会满足你的要求。如果这是真的,那么您可能需要使用MapReduce,或者可能需要使用Baju的方法(还没有测试过)这是行不通的<代码>未定义的方法在“for User:Class(NoMethodError)”处选中。第二条语句将起作用,因为您正在传入一个对象。我需要比较属于同一文档/模型的两个字段。我需要你发布你的用户类——只是mongoid include和checked_at和你的scope的定义。我用用户类编辑了原始问题。谢谢你的时间,杰西。太棒了,这很好用。还感谢您的性能建议。
class User
include Mongoid::Document
include Mongoid::Paranoia
include Mongoid::Timestamps
field :checked_at, :type => Time
scope :unresolved, lambda{ |user| where(:updated_at.gt => user.checked_at) }
end