Single Table Inheritance

What is Single Table Inheritance ? Single Table Inheritance is a mechanism through which ActiveRecord can share fields and behavior between different models. For eg. let’s say we need to create a model vehicle and car. Since vehicle and car will share their attributes and methods we can use Single Table Inheritance on them. Let’s generate vehicles model and a cars model with vehicles as its parent: rails generate model vehicle type:string color:string price:decimal{10....

April 12, 2024 · 2 min · Ashish Gaur

Polymorphic Associations

What is Polymorphic Associations ? With Polymorphic Association a model can belong to more than one models with a single association. Let’s take an example, we’ll use polymorph associations on the following schema: In the above schema picture belongs to both employee and products. Creating picture model with polymorphic association will look like this: class Employee < ApplicationRecord has_many :pictures, as: :imageable end class Product < ApplicationRecord has_many :pictures, as: :imageable end class Picture < ApplicationRecord belongs_to :product, as: :imageable belongs_to :employee, as: :imageable end Now we can use Picture model with Product and Employee:...

April 12, 2024 · 1 min · Ashish Gaur

Eager Loading

What is Eager Loading ? Eager loading is a mechanism through which ActiveRecord loads the associated records of an ActiveRecord object in memory, reducing the number of executed sql queries. There are 3 ways to do eager loading in ActiveRecord: includes preload eager_load Why do we need Eager Loading ? Let’s say we’ve to get the author’s last name of some books. For that the query will look like:...

April 11, 2024 · 3 min · Ashish Gaur