2010-09-25 17 views
5

我需要在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 

这给了我下面的错误:

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

回答

7

据我所知,MongoDB的不支持针对动态值的查询。 但是你可以使用JavaScript函数:

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

加快这你可以添加属性,如“is_unresolved”当这个条件匹配将被设置为true更新(和索引)。

+0

太棒了,这个作品很棒。也感谢您的性能建议。 – 2010-10-18 05:54:01

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

例如,这将工作:

scope :foo, where(:start_date.lte=>Date.today.midnight) 
+1

这是行不通的。未定义方法'checked_at'为User:Class(NoMethodError)'。第二条语句将起作用,因为你正在传入一个对象。我需要比较两个属于同一文档/模型的字段。 – 2010-09-25 23:26:17

+0

需要你发布你的用户类 - 只是mongoid包括和checked_at的定义和你的范围 – 2010-09-26 12:28:05

+0

我用User类编辑了原始问题。感谢你的时间到目前为止杰西。 – 2010-09-26 22:28:30

1

不知道你是否会喜欢这种方法,它不是最好的,但它应该工作。

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_user_object) 重读您的文章,这将可能不是你想要做什么之后,现在看来调用它。如果这是真的,那么你可能需要使用MapReduce或可能Baju的方法(没有测试过)