rails-activerecord

26
Active Record in Rails by Farhan Faruque

Upload: farhan-faruque

Post on 10-Aug-2015

73 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Rails-activerecord

Active Record in Railsby Farhan Faruque

Page 2: Rails-activerecord

Topics

❏ Basics❏ Active Record Migrations❏ Active Record Validations

Page 3: Rails-activerecord

Active Record- What?

❏ an ORM (Object Relational Mapping).❏ a layer of Ruby code that runs between your

database and your logic code.

Page 4: Rails-activerecord

Convention over Configuration● if you configure your applications in the very same way most of the time

then this should be the default way● 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

BookClub book_clubs

Post Posts

Page 5: Rails-activerecord

Creating Active Record ModelsModel

class Post < ActiveRecord::Base attr_accessor :title,:descend

Database

CREATE TABLE Posts ( id int(11) NOT NULL auto_increment, title varchar(255), desc text, PRIMARY KEY (id));

Page 6: Rails-activerecord

CRUD: Reading and Writing Data

Create

post = Post.create(title: ‘Cricket WC’,desc:’2015 Australia’) Read

post = Post.all # return a collection with all users

post = Post.where(title:’Cricket WC’)Update

post = Post.find_by(title:’Cricket WC’)post.desc = ‘Cricket World cup - 2015’post.save

deletepost.destroy

Page 7: Rails-activerecord

Migrations - Basic

❏ Alter Database and Schema in a consistent way❏ database independent❏ each migration as being a new 'version' of the database

Page 8: Rails-activerecord

Migration - Example$ rails generate model location name:string description:textclass CreateLocation < ActiveRecord::Migration def change create_table :location do |t| t.string :name t.text :description t.timestamps null: false end endend

Page 9: Rails-activerecord

Creating Migration$ rails generate migration AddStreetToLocations street:stringclass AddStreetToLocation< ActiveRecord::Migration def change add_column :locations, :street, :string endend

● stored as files in the db/migrate directory● The name of the file is of the form YYYYMMDDHHMMSS_add_street_to_location.rb

Page 10: Rails-activerecord

Migration - convention

Convention Example Generates in Change

AddXXXToXXX AddStreetToLocation street:string add_column :locations, :street, :string

RemoveXXXFromXXX RemoveStreetFromLocation street:string

remove_column :location, street :string

CreateXXX CreateLocation create_table :location

XXXRefToXXX AddCountryRefToLocation add_reference :Location, :country, index: true

XXXJoinTableXXX CreateJoinTableCustomerProduct customer product

create_join_table :customers, :products

Page 11: Rails-activerecord

Changing table and column

change_column :location, :latitude, :string

change_table :products do |t| t.remove :description, :nameend

Page 12: Rails-activerecord

Migration - Passing Modifiers$ bin/rails generate migration AddDetailsToProducts 'price:decimal{5,2}'class AddDetailsToProducts < ActiveRecord::Migrationdef change add_column :products, :price, :decimal, precision: 5, scale: 2 endendModifiers Type● limit● required● default● etc..

Page 13: Rails-activerecord

Using the up/down Methods❏ same as change method❏ used before rails-3.1❏ up method use for transformation❏ down method for revert up

Page 14: Rails-activerecord

Running Migration❏ $ rake db:migrate

- run current migration❏ $ rake db:migrate VERSION=20080906120000

- run specific version❏ $ rake db:rollback

- roll back to previous version❏ $rake db:migrate RAILS_ENV=test

- run migration in test environement

Page 15: Rails-activerecord

Active Record Validations - Why?

❏ ensures valid data❏ model-level validation

Page 16: Rails-activerecord

Others ways of validations problems

❏ Database Constraints- database dependent

❏ Client-side validations- unreliable

❏ Controller-level validations- difficult to test and maintain

Page 17: Rails-activerecord

Example

class Location < ActiveRecord::Base validates :name, presence: trueend

Person.create(name: "John Doe").valid? # => truePerson.create(name: nil).valid? # => false

Page 18: Rails-activerecord

Validation triggers❏ create❏ create!❏ save❏ save!❏ update❏ update!

Page 19: Rails-activerecord

Validations Helpers❏ acceptanceclass Person < ActiveRecord::Base validates :terms_of_service, acceptance: trueend

❏ confirmationclass Person < ActiveRecord::Base validates :email, confirmation: trueend

Page 20: Rails-activerecord

Other Validations Helpers❏ length❏ numericality❏ validates_associated❏ exclusion❏ format❏ presence❏ uniqueness❏ etc..

Page 21: Rails-activerecord

Common options

:allow_nil:allow_blank:message:on

Page 22: Rails-activerecord

Conditional Validation

:if and :unless❏ a symbol :a method name❏ a string :a really short

condition❏ a proc :an inline condition

Example - with a methodclass Order < ActiveRecord::Base validates :card_number, presence: true, if: :paid_with_card?

def paid_with_card? payment_type == "card" endend

Page 23: Rails-activerecord

Custom Validations❏ Inherited from Two moudles

➢ ActiveModel::Validator➢ ActiveModel::EachValidator➢ get the ‘record’ argument as parameter

❏ Custom method and helpers

Page 24: Rails-activerecord

Working with Validation Errors

❏ errors.messages❏ errors[:attr] # for a specific attribute❏ errors.add(:attr,message) ❏ errors[:base] #object’s state as a whole❏ errors.clear #clear errors❏ errors.size #count of errors

Page 25: Rails-activerecord

Displaying Validation in Views

Page 26: Rails-activerecord