rails course day 3

18
Ruby on rails course Day 3

Upload: al-sayed-gamal

Post on 14-Jan-2017

204 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Rails course day 3

Ruby on railscourse

Day 3

Page 2: Rails course day 3

M for Model

Page 3: Rails course day 3

Agenda

ActiveRecord Basics

Associations

Validations

Callbacks

Query Interface

Page 4: Rails course day 3

Active record and MVC

What’s ActiveRecord ?

What to expect from ActiveRecord Model.

associations.

inheritance.

validations.

OO DB operations.

Convention over configuration.

Page 5: Rails course day 3

Active RecordAn object that wraps a row in a database table, encapsulates the database access and adds domain

logic on that data.

Page 6: Rails course day 3

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”)

Page 7: Rails course day 3

Convention over configuration

Model class name and table name

Foreign and primary key convention:

FK: <table_name>_id

PM: id

Page 8: Rails course day 3

Rails g model <model_name> [field:type, ]

Creates model file

Creates model test

Created migration file.

Page 9: Rails course day 3

Associations

belongs_to

has_one

how is that different than belongs_to ?

through

has_many

through

has_and_belongs_to_many

Page 10: Rails course day 3

belongs_to

One2One connection.

single model

belongs_to :department

Page 11: Rails course day 3

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.

Page 12: Rails course day 3

has_manypointing to me.

Page 13: Rails course day 3

has_many through :modelVS. has_and_belongs_to_many

Page 14: Rails course day 3

Self Join

class_name

foreign_key

class Employee < ActiveRecord::Basehas_many :subordinates, class_name: "Employee",foreign_key: "manager_id"

Page 15: Rails course day 3

Validations

Built-invalidates :name, presence: true, length: {minimum: 3}

Class Validator, EachValidator

Template design pattern

Methods

on:

Page 16: Rails course day 3

Call Backs

Before, after and around ->SaveSave<- ->Save<-

When

Create, update, destroy

Save, validate

Executio

n o

rder

Destroy

Update

Create

Page 17: Rails course day 3

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.

Page 18: Rails course day 3

Thank you!