DEV Community

Cover image for Associate with Me: Active Record Associations
Quinn Sissler
Quinn Sissler

Posted on

Associate with Me: Active Record Associations

Associate with Me!

Active Record is an incredibly powerful ORM library. One of the many ways we can use Active Record is to help us simplify our code when using common operations between two associated models. Let's consider a simple school application that includes a model for teachers and a model for students. Every teacher has many students and every student belongs to a teacher. Our table model could look like this:
Teacher and Student Table Model

Our model declarations without Active Record associations would look like this:
Teacher and Student classes

One to Many

The above example shows a one-to-many relationship. To create this association with Active Record, we would declare our models like this:
Teacher and Student classes with Associations

The belongs_to association creates a one-directional connection between the models. With belongs_to, each student in our example model now "knows" its teacher.

The has_many association is typically used in conjunction with the belongs_to association. With has_many, each teacher in our example model now "knows" its students.

With just one line of code added to each class, we now have many built in methods that allow us to effortlessly access related data.

What now?

Now we can use our built in Active Record methods to access related information.

We can ask a teacher about their students.
We can also ask a student about their teacher.

Let's create a teacher instance for Mrs. Smith:
Mrs. Smith Instance

Now to access all of the students that are associated with Mrs. Smith all we have to do is:
Mrs. Smith's Students

Yes! It's that easy!

Let's create a student instance for Johnny:
Johnny Instance

In order to find out who Johnny's teacher is, all we have to do is:
Johnny's Teacher

We can even take it a step further and access Johnny's teacher's name:
Johnny's Teacher's Name

Conclusion

Active Record is a wonderfully efficient tool that simplifies our code when writing association methods for our associated models. Our example today barely scratches the surface on what Active Record can do and I encourage you to check out their documentation to learn more!

Sources:
Rail Guides

Top comments (0)