我有一个GiftCategory
模型:Mongoid:凡has_many关联具有一定的领域对象的查询值
class GiftCategory
include Mongoid::Document
field :gifts_count, type: Integer
has_many :gifts, :inverse_of => :gift_category
end
而且我有一个Gift
模型:
class Gift
include Mongoid::Document
field :gift_units_count, type: Integer
has_many :gift_units, :inverse_of => :gift
belongs_to :gift_category, :inverse_of => :gifts, :counter_cache => true
after_save :update_counter
def update_counter
self.gift_category_id_change.each do |e|
GiftCategory.reset_counters(e, :gifts) unless e.nil?
end
end
end
的update_counter
方法可以让我保持的数有多少个Gift
对象属于GiftCategory
。这样我可以查询仅GiftCategory
对象有一些Gift
对象:
GiftCategory.where(:gifts_count.gt => 0)
但你可以看到,一个Gift
有gift_units_count
领域也是如此。该字段保持Gift
的可用数量单位的计数。如何查询GiftCategory
具有Gift
对象的对象gift_units_count > 0
?
我认为解决方案可能类似here,但我无法靠近自己。
如果您需要一个条件:'GiftCategory.where(:id.in => gift_category_ids)' – drinor