-1

I have a user and project model created in Rails. I have to perform an association that will create an relationship which is described below:

1 User has many Projects

1 project has many Users

How can I go about creating an association for the same in Rails? I need some help on which type of association in rails will help me to achieve this.

Pooya
  • 6,083
  • 3
  • 23
  • 43
Ahkshay Ravi
  • 49
  • 1
  • 6

5 Answers5

2

You are describing a many-to-many relationship type. Rails allows you to create this relationship using has_many :through and has_and_belongs_to_many directives. You can learn the difference here.

Shortly, has_many :through allows you to add additional columns into the intermediate table, has_and_belongs_to_many doesn't. If you don't need to have additional attributes in the intermediate table than use has_and_belongs_to_many syntax. You can always change to has_many :through later.

class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :projects
end
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
0

You can use has_and_belongs_to_many or has_many through.Here is the link I am providing which will help you to sort out difference between them and which one will be good for you.Here is the video tutorial for you association.ALso there is a good link link.In your case you need has and belongs to many

Community
  • 1
  • 1
Aniket Tiwari
  • 3,561
  • 4
  • 21
  • 61
0

You are basically trying to have a many-to-many relationship.

In Rails you can do this based on two association concept:

  1. has_and_belongs_to_many (HABTM)

  2. has_many :through

Note:

You should have HABTM if you just do not care about the way these two tables are joined (relationship model) and you do not want to have any logic/validation for your join data. It will just keep your foreign keys in a table and based on that data will be fetched.

You need has_many :through if you want to have an intermediate model in between Project and User which can be called as UserProject model. This way your association could look like as follows:

User Model:

has_many :user_projects
has_many :projects, through: :user_projects 

Project Model:

has_many :user_projects
has_many :users, through: :user_projects

UserProject Model:

belongs_to :user
belongs_to :project
dp7
  • 6,651
  • 1
  • 18
  • 37
0

You may want too use many to many relationship between project and user. on top of that you may want to visit rails official guide which describes all of these relations in great detail.

http://guides.rubyonrails.org/association_basics.html

Ccr
  • 686
  • 7
  • 25
0

The best thing to do in this situation is , In your user.rb model file:

has_and_belongs_to_many :projects

and In your project.rb model file:

has_and_belongs_to_many :users
Abhilash Reddy
  • 1,499
  • 1
  • 12
  • 24