1

我试图建立一种基本上如下的关系:

组模型

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。但是,我不知道如何从用户加入的组中查询所有帖子。任何建议表示赞赏!

4

2 回答 2

2

你要

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :posts
  has_many :group_posts, through: :groups, source: :posts
end
于 2013-10-01T15:09:33.160 回答
0

一些进一步的阅读:has_many :through

has_many :通过关系

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
于 2013-10-01T15:39:39.167 回答