Search code examples
ruby-on-railsruby-on-rails-3activerecordassociationsmodels

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!


Solution

  • 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