rails course day 3
TRANSCRIPT
Ruby on railscourse
Day 3
M for Model
Agenda
ActiveRecord Basics
Associations
Validations
Callbacks
Query Interface
Active record and MVC
What’s ActiveRecord ?
What to expect from ActiveRecord Model.
associations.
inheritance.
validations.
OO DB operations.
Convention over configuration.
Active RecordAn object that wraps a row in a database table, encapsulates the database access and adds domain
logic on that data.
What to expect from ActiveRecord Model?
associations.
Relations to different models to simulate one2many, many2one self joins, etc..
inheritance.
also is considered as relation however it’s parent-child relationship between models.
validations.
validation logic
OO DB operations.
Business logic example:
ahmed = User.last ahmed.joined_course(“math”)
Convention over configuration
Model class name and table name
Foreign and primary key convention:
FK: <table_name>_id
PM: id
Rails g model <model_name> [field:type, ]
Creates model file
Creates model test
Created migration file.
Associations
belongs_to
has_one
how is that different than belongs_to ?
through
has_many
through
has_and_belongs_to_many
belongs_to
One2One connection.
single model
belongs_to :department
has_one
has_one is One2One connection.
single model
has_one <model>
No FK required in model, it’s pointed in the other model.
through is the intermediate junk table.
has_manypointing to me.
has_many through :modelVS. has_and_belongs_to_many
Self Join
class_name
foreign_key
class Employee < ActiveRecord::Basehas_many :subordinates, class_name: "Employee",foreign_key: "manager_id"
Validations
Built-invalidates :name, presence: true, length: {minimum: 3}
Class Validator, EachValidator
Template design pattern
Methods
on:
Call Backs
Before, after and around ->SaveSave<- ->Save<-
When
Create, update, destroy
Save, validate
Executio
n o
rder
Destroy
Update
Create
Query interface
find(id or array(id))
take, first, last
find_by(key: value)*
where
? for sql injection
hash conditions
Ordering
Selecting
Group and Having
includes*
limit and offset
*find_each will be used with huge amount of records *includes will eager load all associated models for less queries.
Thank you!