2010-11-19 56 views
0

我有嵌入用戶的通知。在Mongoid中,我將如何實現類似的查詢。下面的查詢使用Mongdb完成:Mongoid,通知幫助

MONGODB site_name_development['users'].update(
    {"_id"=>BSON::ObjectId('4ce694e672357e015a000014'), 
    "notifications._id"=>BSON::ObjectId('4ce694e672357e015a000017')}, 
{"$set"=>{"notifications.0.is_active"=>true}}) 

基本上,如果我有用戶Foobar。 Foobar有3種類型的通知。我想通過將is_active設置爲true來打開其中一個通知。同時所有其他通知的is_active應該設置爲false

應該執行什麼查詢?

回答

0

等效代碼將是這樣的:

notification = User.find('4ce694e672357e015a000014').notifications.find('4ce694e672357e015a000017').update_attributes!(:active => true) 

如果當時就想設置別人爲無效:

User.find('4ce694e672357e015a000014').notifications.excludes(:id => '4ce694e672357e015a000017').each { |notification| notification.update_attributes!(:active => false) } 

或者你可以做到這一點的一條線,我猜。

User.find('4ce694e672357e015a000014').notifications.each { |notification| notification.update_attributes!(:active => (notification.id == '4ce694e672357e015a000017' ? true : false)) } 
0

戴夫基本上是正確的,但最新的mongoid有一個方法叫update_all,你可以利用它來進行設置其他通知停用:

User.find('4ce694e672357e015a000014').notifications.excludes(:id => '4ce694e672357e015a000017').update_all(:active => false)