2010-05-05 97 views
4

我有什麼,我認爲是一個很簡單的問題(鬼才)...Rails的找到所有與關聯

我有一個Category模型has_and_belongs_to_manyEvents。我想構建一個簡單高效的查詢,查找具有一個或多個事件的所有類別。 (使用Rails 3)

我敢肯定,我在這裏一個愚蠢的時刻 - 感謝任何幫助:)

回答

8

如何:

Category.find :all, 
    :conditions => 'id in (select distinct category_id from categories_events)' 

你也可以將其添加爲命名的範圍您Category類,這樣你可以說Category.with_events

class Category < ActiveRecord::Base 
    named_scope :with_events, 
    :conditions => 'id in (select distinct category_id from categories_events)' 
end 
+0

謝謝,很好的伎倆。 – aaronrussell 2010-05-05 12:16:36