Active Record Associations

Sean Ngo
2 min readJun 4, 2021

--

Active record is the model or layer of the system responsible for representing data and logic. It is responsible for creating and using objects whose data requires us to continually persist storage to the database. Active record itself is an ORM, that makes fetching and representing data easier. By using active record it saves us the trouble of writing our own custom ORM’s.

Active record associations allow us to associate models and their related database tables without having to write an endless amount of code. With associations we can streamline certain methods such as creating and destroying. There are six types of associations, the main three that we’ve worked with so far are belongs_to, has_many, and has_many :through. The other three are has_one, has_one :through, and has_and_belongs_to_many.

A belongs to association sets up a connection with another model, so that the instance of the declaring model “belongs_to” one instance of the other model.

Here we’re telling the Role class that it will produce objects that can belong to a movie and actor. We now have to tell the actor class that each actor object has many roles and movies through the connecting roles class.

We now have to do they same with the Movie class so that it can read the other models

It is typically better to update the has_many side of a relationship to get the full benefit of Active records capabilities. But as we can see, with associations we can start to build out and persist associations between things.

--

--