Ruby on Rails Introduction

Preview:

DESCRIPTION

Ruby on Rails introduction.

Citation preview

Ruby on Rails

Introduction to Ruby

Ruby Syntax and Concepts Variables Constants Blocks Hashes

Rails Principles and patterns

DRY Convention Over Configuration Active Record Patern MVC

Model

the model - which is the layer of the system responsible for representing business data and logic

In Rails ActiveRecord is represents a Model

The interface of an object conforming to this pattern would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.

ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications

Active Record as an ORM Framework: DataMapper and Sequel show major improvements over the original ActiveRecord framework

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.

Convention over configuration

Naming Conventions Database Table - Plural with underscores separating words (e.g., book_clubs) Model Class - Singular with the first letter of each word capitalized (e.g., BookClub)

Model / Class Table / Schema

Post posts LineItem line_items

Creating an active record Models

SQL CREATE TABLE products ( id int(11) NOT NULL auto_increment, name varchar(255), PRIMARY KEY (id) ); class Product < ActiveRecord::Base end

Creating active record

user = User.create(name: "David", occupation: "Code Artist")

user = User.new user.name = "David" user.occupation = "Code Artist"

user.save

Reading an activerecord from database

users = User.all user = User.first david = User.find_by(name: 'David') users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')

Updating Activerecords attributes

user = User.find_by(name: 'David') user.update(name: 'Dave') Destroying an ActiveRecors user = User.find_by(name: 'David') user.destroy

Validation

create create! save save! update update!

Validations

class Person < ActiveRecord::Base validates :name, presence: true end Person.create(name: "John Doe").valid? # => true Person.create(name: nil).valid? # => false

Following methods skip validation call decrement! decrement_counter increment! increment_counter toggle! touch update_all update_attribute update_column update_columns update_counters

Validation Helpers

Acceptance class Person < ActiveRecord::Base validates :terms_of_service, acceptance: true end

validates_associated

class Library < ActiveRecord::Base has_many :books validates_associated :books end

Length class Person < ActiveRecord::Base validates :name, length: { minimum: 2 } validates :bio, length: { maximum: 500 } validates :password, length: { in: 6..20 } validates :registration_number, length: { is: 6 } end Uniqueness class Account < ActiveRecord::Base validates :email, uniqueness: true end

CallBacks

class User < ActiveRecord::Base validates :login, :email, presence: true before_validation :ensure_login_has_a_value protected def ensure_login_has_a_value if login.nil? self.login = email unless email.blank? end end end

Order and list of Model Call Backs

Migration

A DSL provided by rails to manage Database schema class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.text :description t.timestamps end end end

Rails generator to manage migrations $ rails generate migration AddPartNumberToProducts or $ rails generate migration add_part_number_to_product part_number:number or $ rails generate model Product name:string description:text Using generator to create a migration for removing Part from products $ rails generate migration RemovePartNumberFromProducts part_number:string

Running a migration $ rake db:migrate Rolling Back $ rake db:rollback

Assocaiations

class Customer < ActiveRecord::Base end class Order < ActiveRecord::Base end @order = Order.create(order_date: Time.now, customer_id: @customer.id)

class Customer < ActiveRecord::Base has_many :orders, dependent: :destroy end class Order < ActiveRecord::Base belongs_to :customer end @order = @customer.orders.create(order_date: Time.now)

Types of association

belongs_to has_one has_many has_many :through has_one :through has_and_belongs_to_many

belongs_to

class Order < ActiveRecord::Base belongs_to :customer end

has_one

has_one :through

has_many :

The has_many :through Association

The has_and_belongs_to_many Association:

Controller

C Of MV(C) in rails

Routing: request from browser GET /patients/17

routes.rb get '/patients/:id', to: 'patients#show' resources :doctor

CRUD, Verbs, and Actions

Thank You