Home > OS >  How to deal with 2 different type of associations with same table in rails?
How to deal with 2 different type of associations with same table in rails?

Time:06-14

I am creating my first rails application and stuck at this point for a long time. So I have two models in my project.

  1. Users (created through devise gem)
  2. Projects

There are two associations of these two models with each other. As each project can have multiple developers so I have created the has_and_belongs_to_many association between user and projects. Whenever I need to add a developer I simply do @project.users << current_user

There is another association too and that association is one to many association. It has been created to keep track of the manager of each project which can be only one per project. So I have added a foreign key with the name manager_id in projects table with manager_id referencing to a record in users model.

Now I want to ask how will I add, delete and retrieve this manager of each project. If I do @project.manager << current_user, I get an error message that there is no method named manager and if I do @project.users << current_user, I think it will get added to has_and_belongs_to_many association.

Currently my user model is like this

class User < ApplicationRecord
  has_many :projects, foreign_key :manager_id
  has_and_belongs_to_many :projects 
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
end

And my projects model is like this:

class Project < ApplicationRecord
  belongs_to :users, foreign_key :manager_id
  has_and_belongs_to_many :users
end

CodePudding user response:

You can't have two associations with the same names

You have to rename one association

For example

class User < ApplicationRecord
  has_many :manager_projects, class_name: 'Project', foreign_key :manager_id
  has_and_belongs_to_many :projects 
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
end
class Project < ApplicationRecord
  belongs_to :manager, class_name: 'User', foreign_key :manager_id
  has_and_belongs_to_many :users
end

CodePudding user response:

After following the steps told by Stefanyuk Yuriy and then taking help from some other resources I was finally able to solve the problem. I modified my model classes like this

User.rb:

class User < ApplicationRecord
      has_many :projects_as_project_manager, class_name: 'Project', foreign_key: :manager_id
      has_and_belongs_to_many :projects
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :validatable
    end

Project.rb:

class Project < ApplicationRecord
  belongs_to :project_manager, class_name: 'User', foreign_key: :manager_id
  has_and_belongs_to_many :users
end
  • Related