2014-12-28 27 views
0

我有以下型號:通過關係導軌獲取所有元素?

class Topic < ActiveRecord::Base 
    has_many :topic_tags 
    has_many :tags, through: :topic_tags 
end 

class Tag < ActiveRecord::Base 
    STATUS_DISABLED = 0 
    STATUS_ENABLED = 1 

    has_many :topic_tags 
    has_many :topics, through: :topic_tags 
end 

我whant知道如何讓所有議題,其中狀態STATUS_ENABLED所有標籤。

我想是這樣的:

Topic.where(tags: {status: Tag::STATUS_ENABLED) 

如何最好的方式做到這一點?

編輯:

我找到挑剔的解決方案:

Tag.includes(:topics).where(status: Tag::STATUS_ENABLED).map(&:topics).flatten 

更好的辦法?

回答

2

這應該工作:

Topic.joins(:tags).where(tags: {status: Tag::STATUS_ENABLED}).group("topics.id") 

這適用於內連接。它比你的tags.map(&:topics).flatten解決方案好得多。 map + flatten會爲每個啓用標記查詢數據庫一次。這樣它只有1個查詢。