How ActiveRecord Acts as a Ruby Abstraction to Replace Join Methods in Many to Many Relationships

When creating a many-to-many relationship in our ruby code, there are six basic methods we check off in order to represent the relationship model. In this piece, I will explore how these methods can be replaced by ActiveRecord commands.

What is ActiveRecord

ActiveRecord is a gem (Ruby library) that provides Object Relational Mapping (ORM) to our Ruby codebase using inheritance. Object Relational Mapping is when you are relating elements in a data spreadsheet to elements of a Ruby program. Each row of the spreadsheet is made into a Ruby object, and you can also take a Ruby object and insert it as row into the spreadsheet. ActiveRecord also abstracts the methods that we use to represent many-to-many in our Ruby classes.

Many-to-many relationships are a staple in all code languages and Ruby is no exception. Let’s take a classic three-model many-to-many relationship and look at the methods we use to illustrate them. We are going to use the classes of restaurants, customers and restaurant reviews in our example, where restaurant has many reviews and customer has many reviews, creating a many-to-many relationship between customer and restaurant through reviews.

Ruby code of Many-to-Many relationships before applying ActiveRecord

As the join table, the Review class is initialized with an instance of a restaurant and an instance of a customer. Restaurant class has two methods, one linking it to the Review class and one linking it to Customer class through reviews. Customers has similar two methods, one linking it to Review class and another linking it to Restaurant class through reviews.

ActiveRecord abstracts these six methods into a few lines of code using belongs_to and has_many :through methods.

ActiveRecord abstractions for many-to-many relationships

In these examples, ActiveRecord acts as a superclass and allows you to inherit traits into your program, including has_many , belongs_to and has_many: :through relationships. ActiveRecord has many use cases for our Ruby codebase and replacing join methods is just one of them.

Does anyone want to sketch out the relationship between ActiveRecord and Ruby code improvements? I was thinking has_many through: code_snippets, or has_many through: data pieces.

Comment your thoughts below.