【问题标题】:Mongoid, help with notificationsMongoid,帮助通知
【发布时间】:2010-11-19 16:41:42
【问题描述】:

我在用户中嵌入了通知。在 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 设置为 true 来打开其中一个通知。同时所有其他通知的is_active都应该设置为false

应该执行什么查询?

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    等效的代码是这样的:

    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)) }
    

    【讨论】:

      【解决方案2】:

      Dave 基本正确,但最新的 mongoid 有一个名为 update_all 的方法,您可以使用它来将其他通知设置为非活动状态:

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

      【讨论】:

        猜你喜欢
        • 2011-03-22
        • 2011-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-04
        • 1970-01-01
        • 2021-09-01
        • 2010-11-30
        相关资源
        最近更新 更多