Mongoid - 在查询的地方使用关系字段

时间:2013-09-16 12:36:11

标签: mongoid

我有这个型号:

class Document1
  field privacy
  has_many events, :as => :target
end

class Document2
  field privacy
  has many_events, :as => :target
end

class Event
  belongs_to :target, :polymorphic => true
end

我需要做类似的事情:

Event.where( :target.privacy => :public )

我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

您无法从Mongodb中的关系表中查询字段。 Mongodb没有加入概念。点符号也不适合您,因为您使用的是belongs_to而不是embedded_in。因此,您可以在此处选择一些选项,您可以更改架构以使用嵌入式关系,也可以在3个单独的查询中执行此操作,如下所示:

ids = Document1.where(privacy: :public).pluck(:id) + Document2.where(privacy: :public).pluck(:id)
Event.where(target_id: ids).to_a

我的建议是检查您的架构,以更好地利用嵌入式关系,但这取决于您的用例。

答案 1 :(得分:0)

您可能希望查看MongoDB中的dot notation embedded documents