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.

- 24,267
- 8
- 82
- 108

- 11
- 3
-
The question here is how to write code to assing user to a project with has and belongs to many association? – Mirza Memic Jun 27 '16 at 02:39
-
yes! Im not sure where to start T_T – Jon Cho Jun 27 '16 at 02:44
2 Answers
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.

- 1,170
- 8
- 27
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

- 862
- 5
- 9
-
Thanks for responding. How would i then display the users that clicked join into the group? – Jon Cho Jun 27 '16 at 03:02