如何选择与Mongoid具有has_many关系的文档

时间:2012-06-12 19:07:20

标签: mongoid has-many

我知道我的问题很简单,但我需要一些帮助。

我有两个与has_many关系的mongoid类:

class Container
    ...
    has_many: items
    ...
end

class Item
    ...
    field :date, type => Date
    belongs_to: container
    ...
end

我需要在特定日期有物品的所有容器。

这是范围无法按预期工作。它返回两者,包含它的容器,以及在给定日期没有项目的容器:

class Container
    ...
    scope :with_items_on, ->(date){ where(:_id.in => Item.on(date).only(:container_id).distinct(:container_id)) }
    ...
end

.on(date)是范围,可以正确返回给定日期的所有项目。 感谢。

2 个答案:

答案 0 :(得分:1)

<强> Place.rb

has_many :reviews

<强> Review.rb

belongs_to :place

Mongoid 3 不支持

Place.where('reviews.state' => 'published')

答案 1 :(得分:-2)

mongoid查询系统非常强大,所以这个查询可以归结为一个非常简单的声明。这是一个类方法:

class Container
  #...snip...
  has_many :items

  def self.with_items_on(date)
    where( 'items.date' => date )
  end
end

或作为范围:

class Container
  #...snip...
  has_many :items

  scope :with_items_on, ->(date){ where('item.date' => date) }
end