2012-05-15 17 views
1

可能重複:
How would I grab only articles with comments that were created 20 minutes ago?我將如何抓取所有文章並按評論數量排序?

使用的MongoDB和mongoid。如何通過評論的數量獲取所有文章和訂單?

class Article 
    include Mongoid::Document 

    has_many :comments 
end 

class Comment 
    include Mongoid::Document 

    belongs_to :article 
end 
+2

添加計數器緩存(也許[這一個](https://github.com/jah2488/mongoid-magic-counter-cache)),並可以很容易對自己? –

+0

我想過使用計數器緩存,但只是好奇,看看是否有另一種方式,通過計數意見 –

+2

不,沒有其他好方法。如果您希望效率更高,則必須使用計數器緩存。請確保在計數器緩存字段中添加索引。 –

回答

1

我不知道你是打算進行排序的方向,所以我包括兩個指標 - 你應該刪除一個,如果你不打算使用它,但是這應該做的伎倆爲您提供:

class Article 
    include Mongoid::Document 

    field :comments_count, :type => Integer, :default => 0 
    index [[ :comments_count, Mongo::ASCENDING ]] 
    index [[ :comments_count, Mongo::DESCENDING ]] 
    has_many :comments 

    before_save :update_comments_count 

    protected 
    def update_comments_count 
    self.comments_count = self.comments.count 
    end 
end 
相關問題