1

私の問題が些細なものであることはわかっていますが、助けが必要です。

私は関係を持つ2つのモンゴイドクラスを持っています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

Place.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 に答える