2014-02-14 41 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) 
相關問題