Earlier when programmer used to build a web application, they required the skills to code in both business logic language and database language. However now, back-end frameworks are using Object-Relational Mapping (ORM). It helps programmer store the objects in the database and fetch them as an object of the class. The ORM used in Rails is Active Record. In this article, we'll look deep into Active Record.
ORM is a layer of Ruby code that runs between the database and the logic code. Classes (not necessarily all) in database are represented with tables and rows with records. To form a table in database you write a construct in form of migration in Ruby code, and then run migrations. These migrations make the changes to the database. Rails can handle pretty much all of databases, you just need the required adapter for the database.
Example of migration:
class Employee < ActiveRecord::Migration
def change
create_table :Employee do |t|
t.string :first_name
t.string :last_name
t.integer :age
t.timestamps
end
end
end
Migration are classes. This migration creates a table named "employees" in the database. This table has six columns (id, first_name, last_name, age , created_at, updated_at). t.timestamps creates two more columns in our table: created_at and updated_at. These columns are of type datetime.
There are number of methods, that you can use in migration files.
add_column
add_index
add_timestamps
change_column
change_table
create_table
drop_table
remove_column
remove_index
remove_timestamps
rename_column
rename_index
rename_table
How to create a record from rails console?
e1 = Employee.create first_name: "John", last_name: "Donut", age: 22
INSERT INTO "employees" ("age", "created_at", "first_name", "last_name", "updated_at") VALUES (?, ?, ?, ?, ?) [["age", 22], ["created_at", Fri, 13 Dec 2014 16:02:18 UTC +00:00], ["first_name", "John"], ["last_name", "Donut"], ["updated_at", Fri, 13 Dec 2014 16:02:18 UTC +00:00]]
Active Record uses the database API to insert record in database. Validations and callbacks are some pretty featured of active record. Validate check the integrity of data before inserting into the database. Callbacks are hooks that are called in the lifespan of the object.
Associations
Relational databases have multiple tables that are connected in some way. Active record does through Active Record Associations.
Active Record queries:
emploees = Employee.all
emp2 = Employee.find 2
Employee.first
Employee.last
Employee.where("first_name like 'A%'")
0 Comment(s)