【问题标题】:How to select parent record with specific condition on child record?如何在子记录上选择具有特定条件的父记录?
【发布时间】:2012-08-18 09:25:36
【问题描述】:

我正在使用 Rails 3 和 MongoDB(mongoid 适配器)构建一个应用程序。 我正在努力在子记录中找到具有特定条件的父记录。

class Food
  include Mongoid::Document
  has_many :subscriptions, as: :subscribable
end

class Subscription
 include Mongoid::Document
 field :subscriber_id
 belongs_to :subscribable, polymorphic: true
 belongs_to :subscriber
end

我想选择特定用户尚未订阅的食物。

这是我的查询无效。

Food.not_in('subscriptions.subscriber_id' => [User.first.id])

但它会返回所有食物。 我的查询有什么问题?

感谢任何帮助。

谢谢

【问题讨论】:

  • 你用的是什么版本的 Mongoid?

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid has-many-polymorphs


【解决方案1】:

这样的查询在 Mongoid 中不起作用。以下查询需要加入两个集合,但 MongoDB 没有加入的概念。因此,当您查询时,您只能使用您正在查询的集合中文档的字段 - 在这种情况下,它是 foods 集合(很可能)。

如果您不想根据订阅来查询食物,我建议您在食物中嵌入Subscription。如here所述。

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 2017-07-15
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多