我试图建立一种基本如下的关系:
群组模型
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。但是,我无法弄清楚如何查询用户加入的组中的所有帖子。任何建议表示赞赏!
答案 0 :(得分:2)
你想要
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
has_many :posts
has_many :group_posts, through: :groups, source: :posts
end
答案 1 :(得分:0)
进一步阅读: has_many :through
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