Gabe
Gabe

Reputation: 1249

Rails Active Record Association Issue

I have a project in which the following models are set up:

class User < ActiveRecord::Base
has_and_belongs_to_many :projects
has_and_belongs_to_many :user_roles

class Project < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :user_roles

class UserRole< ActiveRecord::Base
has_and_belongs_to_many :users
belongs_to :project

My problem arises when I want to return every project a user has been involved with and what user role(s) they had on the project including any projects they have worked on and had no assigned user role for

I have a feeling has_many :through might work but I'm not sure exactly how it would work. Any thoughts would be greatly appreciated!

Upvotes: 0

Views: 102

Answers (1)

Aayush Kumar
Aayush Kumar

Reputation: 1618

class User < ActiveRecord::Base
  has_many :user_roles
  has_many :projects, :through => :user_roles


class Project < ActiveRecord::Base
  has_many :user_roles
  has_many :users, :through => :user_roles


class UserRole< ActiveRecord::Base
  belongs_to :user
  belongs_to :project

Upvotes: 1

Related Questions