Ask A Question


You’re not receiving notifications from this thread.

has_and_belongs_to_many associations

Lauro asked in Rails

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

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


class Collaboration < ApplicationRecord
  belongs_to :user
  belongs_to :project

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:

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,149+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.