2013-10-01 53 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