【问题标题】:Mongoid querying inclusion ArrayMongoid 查询包含数组
【发布时间】:2012-04-17 18:33:32
【问题描述】:

我正在我的 rails 网站中实现用户设置,用户可以控制谁可以向他发送通知。可以向他发送信息的用户的允许分类存储在一个数组中,可以由用户设置。

如何根据发帖用户的用户类型查询用户发送通知。

我想做这样的事情。

notifiable_users = User.all.or("notification_setting.posted_by" includes "sender.user_type")

【问题讨论】:

  • all.or 应该是什么意思?
  • 我只是使用 mongoid 的 or 链向所有用户添加过滤器。
  • 但是这样做,我猜你先加载所有用户,然后过滤内存中的对象,为什么不直接进行更精确的查询以降低db调用?
  • @apneadiving mongoid 中的大多数标准方法也是模型方法,即您可以同时使用Model.all.where(...)Model.where(...),但or 不是模型方法,仅适用于标准,所以有必要做Model.all.or(...)。现在开始过滤内存中的对象,但情况并非如此,mongoid 使用标准对象创建查询并懒惰地评估它们。因此,在您对无法链接添加到查询的条件使用某种方法之前,它不会向数据库询问结果。详情请参考mongoid.org/docs/querying/criteria.html
  • @rubish:我在那里只看到any_of,没有看到or,它是在哪里定义的?同样在 ActiveRecord 中,我担心,在 Mongoid 中也是一样的,.all 会直接触发调用。然后首选Model.scoped

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

假设notification_setting.posted_by 是允许的用户类型的数组,sender.user_type 是发件人的 user_type(单数,不是数组),您可以简单地这样做:

notifiable_users = User.all.or("notification_setting.posted_by" => sender.user_type)

如果反过来:

notifiable_users = User.all.or("notification_setting.posted_by".to_sym.in => sender.user_types)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2020-12-30
    • 2014-04-21
    相关资源
    最近更新 更多