2012-07-27 28 views
0

我研究了很多,找不到我的問題的答案。我有我的Rails應用以下設置:Postgres在Rails上加入查詢

class Group < ActiveRecord::Base 
    has_many :people 
    # ... 
end 

class City < ActiveRecord::Base 
    has_many :people 
    # ... 
end 

class Person < ActiveRecord::Base 
    belongs_to :city 
    belongs_to :group 
    # ... 
end 

人民有列:role01

我想讓所有至少有一個人的團體擁有role == 0和一個人擁有role == 1

有什麼想法?順便說一句,我正在使用Postgres。

回答

1

這裏我只是在我的sqlite3的數據庫測試查詢(應在Postgres的工作太相信):

Group.select("groups.*").joins("LEFT JOIN people on groups.id = people.group_id").where("people.role==0 OR people.role==1").group("id") 

在這裏,我假設你已經添加了外鍵GROUP_ID在你的人遷移。希望這可以幫助。