DEV Community

Josephine Luu
Josephine Luu

Posted on • Updated on

Active Record Associations

What are Active Record Associations?

Association is the relationship between models and it's used to make it easier on coders like you. Let's dive into the different types of associations with a example for each.

The 6 Types of Associations

1.belongs_to
A belongs_to association creates a connection with another model. The associations has to be used in a singular term because Rails will automatically infer the class name from the association name. In this example, each review can be assigned to exactly one user. It will look for a user_id on the reviews table.

Image description

2.has_one
A has_one association indicates that one other model has a reference to this model. For example, each supplier only has one account. The account will be associate with supplier_id.

Image description

3.has_many
A has_many association is a one-to-many connection with another model. The associations has to be used in a plural term. For example, a user can have many reviews in this example.

Image description

Image description

4.has_many :through
A has_many :through association has a many-to-many connection with another model. The models are connected through another model. For example, a game has many users, through reviews and a user has many games, through reviews. A review belongs to a game and a user.

Image description

The tables will look something like this.
Image description

5.has_one :through
A has_one :through association sets a one-to-one connection with another model but can proceed through a third model. For example, if a department has one manager, and each manager is associated with one manager history, then it will look like this:

Image description

6.has_and_belongs_to_many
A has_and_belongs_to_many association is similar to the has_many :through association, but there is no third model. For example, there was a review model, but now there is only a game and user model.

Image description

There is also a polymorphic association that is more advanced and to learn more about that I would recommend visiting this. I hope this was helpful and good luck coding!

Sources:
-https://guides.rubyonrails.org/association_basics.html
-https://www.youtube.com/watch?v=5mhuNSkV_vQ&t=409s

Top comments (0)