DEV Community

tartope
tartope

Posted on

Ruby and Active Record Associations

Active Record Associations come in handy when working with multiple models (tables) in your database. Having a good understanding of Active Record will make working with data across multiple models easier. Associations you can build are one-to-many and many-to-many associations.

When you have two models a one-to-many association can be used. For example, you have a database with the models: Games and Reviews. In this case, you can imagine that a game can have many reviews, and a review will belong to one game. The Review model will read as "belongs_to :game", and the Games model will read as "has_many :reviews".

When working with multiple models a many-to-many association is used here. Now imagine you have a database with the models: Games, Reviews, and Users. A user can have many reviews and be associated with many games through their reviews. The Review model will read as "belongs_to :game", and "belongs_to :users". The Games model will read as "has_many :reviews" and include "has_many :users, through: :reviews". The Users model will read as "has_many :reviews" and include "has_many :games, through: :reviews".

Naming is important when using Active Record associations so be careful to use singular vs. plural naming conventions.

Top comments (0)