I have a GiftCategory
model:
class GiftCategory
include Mongoid::Document
field :gifts_count, type: Integer
has_many :gifts, :inverse_of => :gift_category
end
And I have a Gift
model:
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
The update_counter
method allows me keep count of how many Gift
objects belongs a GiftCategory
. This way I can e.g. query only for GiftCategory
objects that have some Gift
objects:
GiftCategory.where(:gifts_count.gt => 0)
But as you can see, a Gift
has a gift_units_count
field as well. This field keeps count of the number units available of the Gift
. How can I query for GiftCategory
objects that has Gift
objects with gift_units_count > 0
?
I think that a solution could be something like described here, but I can't get closer myself.