1

我知道我的问题是微不足道的,但我需要一些帮助。

我有两个具有关系的 mongoid 类has_many

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)是正确返回给定日期的所有项目的范围。谢谢。

4

2 回答 2

1

地点.rb

has_many :reviews

评论.rb

belongs_to :place

Mongoid 3不支持

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

于 2012-10-19T09:13:44.510 回答
-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
于 2012-06-14T01:02:46.897 回答