Ask A Question

Notifications

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
end

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

end

class Collaboration < ApplicationRecord
  belongs_to :user
  belongs_to :project
end
Reply

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.

Reply

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?

Reply

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

Reply

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.

Reply

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

Reply
Join the discussion
Create an account Log in

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

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

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