gllwrnce
gllwrnce

Reputation: 59

What steps do I need to take to make this one-to-many relationship into a many-to-many?

I've seen some other posts about this but they're dealing with a version of rails that I'm not using (I'm VERY new to rails), and I have this set up:

class ProjectModel < ActiveRecord::Base
     belongs_to:user

And:

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

has_many :project_models

I need to know what steps I have to take in order to change this into a many-to-many migration.

Notes: This is for a group project and its my part to set it up so that the projects have a list of users assigned to them, and this list needs to be able to have members added to or deleted from, so I'm not sure whether there needs to be a has_and_belongs_to_many or a has_many:through set up.

Any other info that you could give me would be greatly appreciated but since I'm so new to rails I don't even really know how to do this migration (I only know how to do a one-to-many migration using something like AddAuthorRefToBooks authors:references, if we were working with an example like that).

Upvotes: 1

Views: 51

Answers (1)

charlysisto
charlysisto

Reputation: 3700

You need to add an intermediary Model e.g.

class ProjectParticipant
  belongs_to :user
  belongs_to :project
end

class Project
  has_many :project_participants
  has_many :users, through: :project_participants
end

class User
  has_many :project_participants
  has_many :projects, through: :project_participants
end

You can start out with the following so it will also generate the migration you need to create the table.

rails g model project_participant project:references user:references

or the equivalent

rails g model project_participant project_id:integer user_id:integer

Upvotes: 1

Related Questions