Patrick Ng
Patrick Ng

Reputation: 203

Rails - setting up relationship between 3 models and do query

I am trying to build a relationship basically as follows:

Group Model

has_and_belongs_to_many :users
has_many :posts

User Model

has_and_belongs_to_many :groups
has_many :posts

Post Model

belongs_to :group
belongs_to :user

When I query about posts by the user, I can do user.posts. However, I can't figure out how to query all posts from the groups that the user joined. Any suggestion is appreciated!

Upvotes: 1

Views: 116

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Some further reading for you: 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

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44685

You want

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

Upvotes: 2

Related Questions