2010-09-25 63 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的方法(沒有測試過)