Mongoid,帮助的通知
-
26-09-2019 - |
题
我有嵌入在用户通知。在Mongoid,我将如何实现类似的查询。下面的查询使用Mongdb完成的:
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为真把这个通知的一个上。同时所有其它通知的IS_ACTIVE应设置为假
查询什么应该执行?
解决方案
等效代码将是这样的:
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)) }
其他提示
戴夫基本上是正确的,但最新的mongoid有一个方法叫update_all,你可以使用其它的通知设置为无效:
User.find('4ce694e672357e015a000014').notifications.excludes(:id => '4ce694e672357e015a000017').update_all(:active => false)
不隶属于 StackOverflow