Mongoid, help with notifications
-
26-09-2019 - |
Question
I've got notification embedded in user. In Mongoid, how would I achieve a similar query. The query below is done using Mongdb:
MONGODB site_name_development['users'].update(
{"_id"=>BSON::ObjectId('4ce694e672357e015a000014'),
"notifications._id"=>BSON::ObjectId('4ce694e672357e015a000017')},
{"$set"=>{"notifications.0.is_active"=>true}})
Basically, if I have user Foobar. Foobar has 3 types of notifications. I'd like to turn one of this notifications on by setting is_active to true. At the same time all other notification's is_active should be set to false
What query should be executed?
Solution
The equivalent code would be something like this:
notification = User.find('4ce694e672357e015a000014').notifications.find('4ce694e672357e015a000017').update_attributes!(:active => true)
If you then wanted to set the others to inactive:
User.find('4ce694e672357e015a000014').notifications.excludes(:id => '4ce694e672357e015a000017').each { |notification| notification.update_attributes!(:active => false) }
Or you could do it in one line I guess.
User.find('4ce694e672357e015a000014').notifications.each { |notification| notification.update_attributes!(:active => (notification.id == '4ce694e672357e015a000017' ? true : false)) }
OTHER TIPS
Dave is mostly right, but latest mongoid has a method named update_all and you can use that for setting other notifications to inactive:
User.find('4ce694e672357e015a000014').notifications.excludes(:id => '4ce694e672357e015a000017').update_all(:active => false)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow