2013-10-01 58 views
1

我想基本上建立關係如下:導軌 - 3個車型之間建立關係呢查詢

組模式

has_and_belongs_to_many :users 
has_many :posts 

用戶模型

has_and_belongs_to_many :groups 
has_many :posts 

郵政型號

belongs_to :group 
belongs_to :user 

當我查詢用戶的帖子時,我可以做user.posts。但是,我無法弄清楚如何查詢用戶加入的組中的所有帖子。任何建議表示讚賞!

回答

2

你想

class User < ActiveRecord::Base 
    has_and_belongs_to_many :groups 
    has_many :posts 
    has_many :group_posts, through: :groups, source: :posts 
end 
+0

如何查詢從組中的所有帖子的用戶加入了? –

+0

user.group_posts – BroiSatse

+0

獲取錯誤,它顯示「無法在模型中找到源關聯:group_post或:group_posts Post –

0

一些進一步閱讀你:has_many :through

has_many :through relationship

class Physician < ActiveRecord::Base 
    has_many :appointments 
    has_many :patients, through: :appointments 
end 

class Appointment < ActiveRecord::Base 
    belongs_to :physician 
    belongs_to :patient 
end 

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, through: :appointments 
end