2012-11-15 16 views
2

我的下一個型號查詢,使用Mongoid:Mongoid其中使用count

class Album 
    have_many :images 
end 

class Image 
    belongs_to :album 
end 

我想只有有任何圖片專輯:

Album.all.select{ |a| a.images.count > 0 } 

但它返回一個數組,我需要一個Mongoid ::標準。我嘗試使用類似的東西:

Album.where("this.images.count > 0") 

它總是返回0個元素。 我該怎麼做 ?

+0

我不知道,但這個'Album.joins(:圖像)'應該返回一個有至少一個圖像的相冊數組 - 檢查你的身邊:我不太確定。 – MrYoshiji

回答

1

實際上不是一個數組,並且它是一個代理服務器。 你可以檢查日誌,並看到該助力車呼叫.count funcion爲每個專輯(在我的情況2)。

1.9.3-p194 :043 > Album.each { |a| a.images.count } 
    MOPED: 127.0.0.1:27017 QUERY  database=mongo_benchmark collection=albums selector={} flags=[] limit=0 skip=0 fields=nil (0.7441ms) 
    MOPED: 127.0.0.1:27017 COMMAND  database=mongo_benchmark command={:count=>"images", :query=>{"album_id"=>"50e36dd17c71c110ff000001"}} (0.5209ms) 
    MOPED: 127.0.0.1:27017 COMMAND  database=mongo_benchmark command={:count=>"images", :query=>{"album_id"=>"50e36f8f7c71c110ff000004"}} (0.3800ms) 

此外,如果你想獲得的標準對象,你可以做album.images.scoped

如果你有大量的專輯,它會調用數永遠一個,這是不好的。我建議你在這種情況下使用計數器緩存。你可以使用我有一個分支,包括計數器緩存mongoid https://github.com/arthurnn/mongoid/tree/2215-counter_cache

+0

謝謝我不知道計數器緩存。 – drinor