Active Record
Active Record is which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.Object Relational Mapping
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.Active Record as an ORM Framework
Active Record gives us several mechanisms, the most important being the ability to: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.
Naming Conventions
- Table Name - Plural with underscores separating words (e.g.,
book_clubs
). - Model - Singular with the first letter of each word capitalized (e.g.,
BookClub
).
Schema Conventions
-
Foreign keys - These fields should be named following the pattern
singularized_table_name_id
(e.g.,item_id
,order_id
). These are the fields that Active Record will look for when you create associations between your models. -
Primary keys - By default, Active Record will use an integer column named
id
as the table's primary key. This column will be automatically created.
Overriding the Naming Conventions
class
Book < ActiveRecord::Base
self
.table_name =
"my_books"
end
CRUD: Reading and Writing Data
CRUD: Reading and Writing Data
To Create : Book.create(:name => "ABC", :author_id => 3)
To Read :
All Records : Book.all
First Record : Book.first
Find by Name : Book.find_by(:name => 'ABC') - > Return the first book named 'ABC'
Find with Where condition : Book.where(:name => 'ABC') -> Return all book named 'ABC'.
Update :
1. book = Book.find_by(:name => 'ABC')
book.name = 'Abc'
book.save
2. book = Book.find_by(:name => 'ABC')
book.update(:name => 'Abc')
3. book = Book.find_by(:name => 'ABC')
book.update_attributes(:name => 'Abc', :status => 'InActive')
Update all :
Book.update_all(:status => 'Active')
Delete :
book = Book.find_by(:name => 'ABC')
book.destroy
Upcoming Topics :
1. Validations
2. Callbacks
3. Migrations
No comments:
Post a Comment