2014-02-14 42 views
0

我有一个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) 

但你可以看到,一个Giftgift_units_count领域也是如此。该字段保持Gift的可用数量单位的计数。如何查询GiftCategory具有Gift对象的对象gift_units_count > 0

我认为解决方案可能类似here,但我无法靠近自己。

回答

-1

这不是固有可能的,因为文档被引用。

请务必记住,GiftCategory实际上并不包含Gift。相反,Gift记录有一个名为gift_category_id的字段。您基本上需要找到Gift记录,其中有一个gifts_unit_count > 0,然后编译它们的gift_category_id字段的列表,使它们唯一,然后检索这些记录。

这会做什么大概我上面说:

gift_category_ids = Gift.where(:gifts_unit_count.gt => 0).map {|g| g.gift_category_id}.uniq 
for gift_category_id in gift_category_ids 
    gift_category = GiftCategory.find(gift_category_id) 
    # do something with this 
end 

据我所知,Mongoid是不是愿意为你做这样的事情。正如有人在上面提到的,你可能想考虑嵌入,这将允许你以这种方式进行查询,因为这些字段将被存储在同一个文档中。

+0

如果您需要一个条件:'GiftCategory.where(:id.in => gift_category_ids)' – drinor

0

我已经多次尝试为这个问题找到解决方案,并且总是放弃。我刚刚知道如何轻松模仿。它可能不是一种可扩展的方式,但它适用于有限的对象数量。关键是这个句子从这个documentation它说:

返回标准对象的模型上的类方法也被视为作用域,也可以链接。

因此,而不是写update_counter保存钩子函数,为了节省GiftCategory.gifts_count场后,你可以定义一个类的功能,像这样:

def self.with_gifts 
    ids = GiftCategory.all.select{|gc| gc.gifts.gift_units_count > 0}.map(&:id) 
    GiftCategory.where(:id.in => ids) 
end 

的好处是,你可以做各种查询的相关(礼品)模型和返回那些GiftCategory情况下,当这些查询被满足(这是我的情况),最重要的是你可以链进一步查询,像这样:

GiftCategories.with_gifts.where(:some_field => some_value) 
相关问题