0

I created a has_and_belongs_to_many association between users and projects so that a user would be able to join in on a project. The association table exists however, I am unsure how I would create the association.

View

Schema

developer033
  • 24,267
  • 8
  • 82
  • 108
Jon Cho
  • 11
  • 3

2 Answers2

1

I definitely must recommend you to not use has_and_belongs_to_many, because there is no way for you do to callbacks, validations and so on.

It is definitely nice to use a real join model and use has_many, through.

class User
  has_many :project_users, dependent: :destroy
  has_many :projects, through: :project_users
end

class Project
  has_many :project_users, dependent: :destroy
  has_many :users, through: :project_users
end

class ProjectUser
  belongs_to :project, required: true
  belongs_to :user, required: true

  validates :project, uniqueness: { scope: :user }
end

This works very seamlessly, you can do:

User.update(project_ids: [1,5,6,7])

And it will join the user to these project unless any validations fail.

I started out a big project with these tables everywhere, after a few months we started running into duplication issues, bad state of records and it was a hot mess. Using a real join model is so worth it.

davidwessman
  • 1,170
  • 8
  • 27
0

Since you have your project ID inside hidden you could just do this inside JOIN (post) action

def join
  @project = Project.find(params[:project][:id])
  current_user.projects << @project
end

so if you have instance of @project and instance of user - in my example it is current_user( for example if you use devise) then you would just assign them using operator <<

Here is the reference:

http://guides.rubyonrails.org/association_basics.html#has-many-association-reference

Hope it helps

Mirza Memic
  • 862
  • 5
  • 9