From the course: Ruby on Rails 6 Essential Training: Models and Associations

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Has and belongs to many relationships

Has and belongs to many relationships - Ruby on Rails Tutorial

From the course: Ruby on Rails 6 Essential Training: Models and Associations

Start my 1-month free trial

Has and belongs to many relationships

- [Instructor] Let's spend some time working with Has and Belongs to Many relationships. The first question you may want to know is how to know when to use them. You want to use them when an object has many objects that belong to it, but that don't belong to it exclusively. So we have a project that has many collaborators but those collaborators are not exclusive to this project. They can collaborate on other projects too. Or we have a blog post and it has many categories but those categories are not exclusive to the blog post. It doesn't own them in any way. Instead the categories can also be assigned to other blog posts. As we saw in the introduction to this chapter, the Has and Belongs to Many relationship requires a join table between two other tables. That join table holds two foreign keys and the database best practice is to index both those keys together. This join table is going to do its work behind the scenes.…

Contents