What is ORM and how it’s done in rails…?

ORM : Object Relational Mapping

It means we need not retrieve data from Database manually.
Rails uses Active Record for retrieving data from Database using SQL queries. Python uses some other middleware for ORM.

Three points to remember for ORM in general:
1. One class for each table in the database.
2. Objects of the class correspond to rows in the table.
3. Attributes of an object correspond to columns from the row.

Explaining ORM in rails

Let’s take this example:

class College < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :college
end

We add a foreign key for referencing another table:

class CreateColleges < ActiveRecord::Migration
  def change
    create_table :colleges do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreateStudents < ActiveRecord::Migration
  def change
    create_table :students do |t|
      t.string :name
      t.integer :college_id
      t.timestamps
    end
  end
end

Look into this:

1. Student and College are classes and there are corresponding table in the database.
2. Objects of the class Student and College correspond to rows in the table.
3. Attributes of an Student and College such as name correspond to columns from the row.

2.2.2 :003 > college = College.find(17)
  College Load (0.5ms)  SELECT  "colleges".* FROM "colleges" WHERE "colleges"."id" = $1 LIMIT 1  [["id", 17]]
 => #
2.2.2 :004 > college.students
  Student Load (0.7ms)  SELECT "students".* FROM "students" WHERE "students"."college_id" = $1  [["college_id", 17]]
 => #
2.2.2 :005 >

Observe that college.students are converted into SQL queries, to get all students having college_id as '17'.

Student Load (0.7ms)  SELECT "students".* FROM "students" WHERE  "students"."college_id" = $1  [["college_id", 17]]

This is done using ActiveRecord and has_many , belongs_to , has_one etc., are it's methods for which corresponding SQL queries are fired.

What does Active Record do using ORM framework...?

Represent models and their data.
Represent associations between these models.
Represent inheritance hierarchies through related models.
Validate models before they get persisted to the database.
Perform database operations in an object-oriented fashion.

Rails uses Active Record for ORM. All ActiveRecord are ORM but all ORM need not use ActiveRecord.

Leave a Reply

Your email address will not be published. Required fields are marked *