Skip to main content

has_and_belongs_to_many associations

Rails • Asked by 6696

Im building an app where a User belogns to several projects. Is this a good approach to create a "join table" that just tracks which Projects are connected to which Users? Is the Collaboration model necessary?

class User < ApplicationRecord
  has_many :collaborations
  has_many :projects, through: :collaborations
end

class Project < ApplicationRecord
  has_many :collaborations
  has_many :users, through: :collaborations

end

class Collaboration < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

You only wrote that a user needs to be connected to several projects. If you also wanna connect a project to more than one user then this is the way to go, otherwise you could just say user has_many projects.


Thanks Szilard. Yes, a Project needs to have several Users. But Im not sure how to built controllers and views to make the associations. Should I create Controllers and views to the Collaboracion Model?


You shouldn't. You just say user.projects or project.users anywhere.


What @Szilard said is correct - your controllers / views could care less how your models are structured. You just need to know how to query the model from the controller to grab the results you want. They're not that tightly knit.

So in this case, User.first.projects would list all the first users projects, Project.first.users would list all the users associated with the first project. You can call these from any view/controller.


Thanks for the help Szilard and Jacob! I was having a hard time understanding exsactly what was going on with database and structure. Chris's series on building a forum really helped. Undestanding how to strcuture nested attributes. :)

If anyone want to check it out: https://gorails.com/series/how-to-build-a-forum


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.