rails-activerecord
TRANSCRIPT
Active Record in Railsby Farhan Faruque
Topics
❏ Basics❏ Active Record Migrations❏ Active Record Validations
Active Record- What?
❏ an ORM (Object Relational Mapping).❏ a layer of Ruby code that runs between your
database and your logic code.
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
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));
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
Migrations - Basic
❏ Alter Database and Schema in a consistent way❏ database independent❏ each migration as being a new 'version' of the database
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
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
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
Changing table and column
change_column :location, :latitude, :string
change_table :products do |t| t.remove :description, :nameend
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..
Using the up/down Methods❏ same as change method❏ used before rails-3.1❏ up method use for transformation❏ down method for revert up
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
Active Record Validations - Why?
❏ ensures valid data❏ model-level validation
Others ways of validations problems
❏ Database Constraints- database dependent
❏ Client-side validations- unreliable
❏ Controller-level validations- difficult to test and maintain
Example
class Location < ActiveRecord::Base validates :name, presence: trueend
Person.create(name: "John Doe").valid? # => truePerson.create(name: nil).valid? # => false
Validation triggers❏ create❏ create!❏ save❏ save!❏ update❏ update!
Validations Helpers❏ acceptanceclass Person < ActiveRecord::Base validates :terms_of_service, acceptance: trueend
❏ confirmationclass Person < ActiveRecord::Base validates :email, confirmation: trueend
Other Validations Helpers❏ length❏ numericality❏ validates_associated❏ exclusion❏ format❏ presence❏ uniqueness❏ etc..
Common options
:allow_nil:allow_blank:message:on
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
Custom Validations❏ Inherited from Two moudles
➢ ActiveModel::Validator➢ ActiveModel::EachValidator➢ get the ‘record’ argument as parameter
❏ Custom method and helpers
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
Displaying Validation in Views