SlideShare a Scribd company logo
Model Basics
Business Logic Goes Here
What is a Model?
It’s a Ruby Object
Home of your business logic and object rules
ActiveRecord
  The layer in Rails that talks to the database

  Gives you a lot of conventional tools to make manipulating data easy

Home of CRUD
  create, read, update and delete
Think Model - Think Table

               id   Name    Age



                1   Gypsy   12



                2   Storm   14
Think Model - Think Table
 The Model as a whole
                                   id   Name    Age
 is an object
   Calling a method on the
   model effects all data in the
   model                           1    Gypsy   12



                                   2    Storm   14
Think Model - Think Table
 The Model as a whole
                                   id   Name    Age
 is an object
   Calling a method on the
   model effects all data in the
   model                           1    Gypsy   12
 A record in the model
 is also an object
   Calling a method on a record    2    Storm   14
   effects only that record
How do I
get one?
How do I
get one?
Easy!
Become one with
ruby script/generate
in your console!
Tell the generate
                       command what you
How do I               want to generate and
get one?               you can even add in
                       fields.
Easy!
Become one with        $ ruby script/generate model
                       user name:string
ruby script/generate   address:string age:integer
                       admin:boolean
in your console!
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.integer :age
      t.string :address
      t.boolean :admin

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end




What happens after generate?
Rails creates a file representing the new model
you just created called a migration.
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.integer :age
      t.string :address
      t.boolean :admin

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end




What happens after generate?
Rails creates a file representing the new model
you just created called a migration.
Magic Fields
Magic Fields
Rails adds a few magic fields to your model
Magic Fields
Rails adds a few magic fields to your model
  id - this is the record’s unique id. Every model has
  one, even though it doesn’t appear in the migration
Magic Fields
Rails adds a few magic fields to your model
  id - this is the record’s unique id. Every model has
  one, even though it doesn’t appear in the migration
  timestamps
Magic Fields
Rails adds a few magic fields to your model
  id - this is the record’s unique id. Every model has
  one, even though it doesn’t appear in the migration
  timestamps
    created_at - puts a time stamp when a new record
    is created
Magic Fields
Rails adds a few magic fields to your model
  id - this is the record’s unique id. Every model has
  one, even though it doesn’t appear in the migration
  timestamps
    created_at - puts a time stamp when a new record
    is created
    updated_at - puts a time stamp when a record is
    changed
So I have this migration.
Now what?
 Generating the model
 is half the battle
 Now you have to tie it
 into the Rails
 infrastructure
 How? Why, run a rake
 task, of course!
Rake
Rake
Infrastructure that helps
you run common tasks
in Rails easily.
  migrations, run tests
  and many more
Rake
Infrastructure that helps
you run common tasks
in Rails easily.
  migrations, run tests
  and many more
Completely customizable
- create your own rake
tasks
Rake
Infrastructure that helps   For a list of all the rake
you run common tasks        commands, just run
in Rails easily.                  $ rake -T

  migrations, run tests
  and many more
Completely customizable
- create your own rake
tasks
Rake
Infrastructure that helps   For a list of all the rake
you run common tasks        commands, just run
in Rails easily.                  $ rake -T

  migrations, run tests
                            To execute your
  and many more
                            beautifully crafted
Completely customizable     migration, just run
- create your own rake
tasks                           $ rake db:migrate
A bit more about Migrations
                            $ script/generate migration add_email_to_users
 add_column() takes
 the model name, field
 name and data type         class AddEmailToUsers <
                                  ActiveRecord::Migration
                              def self.up
                                add_column :users, :email, :string
 self.down will revert to     end

 the pre-migrated state       def self.down
                                remove_column :users, :email
                              end
 use the same rake          end

 db:migrate to execute
 command
ActiveRecord::Schema.define(:version => 20100301045108) do

  create_table   "users", :force => true do |t|
    t.string     "name"
    t.integer    "age"
    t.string     "address"
    t.boolean    "admin"
    t.datetime   "created_at"
    t.datetime   "updated_at"
  end

end



Meet the Schema file
Rails generates a ‘map’ of your database.This is
the map after the initial model generation
create_table   "users", :force => true do |t|
  t.string     "name"
  t.integer    "age"
  t.string     "address"
  t.boolean    "admin"
  t.datetime   "created_at"
  t.datetime   "updated_at"
  t.string     "email"
end




Schema after migration
Each migration updates and replaces the existing
schema
create_table   "users", :force => true do |t|
  t.string     "name"
  t.integer    "age"
  t.string     "address"
  t.boolean    "admin"
  t.datetime   "created_at"
  t.datetime   "updated_at"
  t.string     "email"
end




Schema after migration
Each migration updates and replaces the existing
schema
Let’s play with some CRUD
Let’s play with some CRUD

CRUD stands for Create, Read, Update and Delete
Let’s play with some CRUD

CRUD stands for Create, Read, Update and Delete
These are the heart of ActiveRecord and the primary
purpose of the model
Let’s play with some CRUD

CRUD stands for Create, Read, Update and Delete
These are the heart of ActiveRecord and the primary
purpose of the model
Between these four actions, you can accomplish pretty
much anything in your database
C is for Create
C is for Create
 Create - adds an
 object to the database
C is for Create
 Create - adds an
 object to the database
                           user = User.new(:name => "Gypsy",
 Two common ways of                        :age => 12)
                           user.save
 achieving this are with
 new() and save() or
 create()
C is for Create
 Create - adds an
 object to the database
                           user = User.new(:name => "Gypsy",
 Two common ways of                        :age => 12)
                           user.save
 achieving this are with
 new() and save() or       user = User.create(:name => "Storm",

 create()                                     :age => 14)



 create() is a combined
 new() and save()
R is for Read

 Read - Retrieves an
 object from the
                         user = User.find(1) # by id
 database                => #<User id: 1, name: "Gypsy", age: 12>

                         user = User.first # first record
 You can find virtually   => #<User id: 1, name: "Gypsy", age: 12>


 anything using          user = User.last # last record
                         => #<User id: 2, name: "Storm", age: 14>

 ActiveRecords find
 methods
Some more Read methods

                         user = User.find_by_name("Storm")
You can pass in          => #<User id: 2, name: "Storm", age: 14, >


arguments to find_by()    users = User.all # returns an array of all users
                         => [#<User id: 1, name: "Gypsy", age: 12>,
                             #<User id: 2, name: "Storm", age: 14>]

You an also use SQL to   user = User.all(:order => 'age DESC')
                         => [#<User id: 2, name: "Storm", age: 14>,
locate data within           #<User id: 1, name: "Gypsy", age: 12>]


specific criteria         user = User.first(:conditions => 'age > 12')
                         => #<User id: 2, name: "Storm", age: 14>
U is for Update

 Update - saves existing
 object with new data      user.update_attributes(
                                       :age   => 15,

 update_attributes()       => true
                                       :email => "storm@gmail.com")


 takes in a Hash of        => #<User id: 2, name: "Storm", age: 15,
                                     email: "storm@gmail.com">
 attributes and saves
 them to the database
D is for Delete

 Delete - removes
 object from database        user = User.find_by_name("Gypsy")
                             user.destroy
 This is an all or nothing   User.find_by_name("Gypsy")
                             => nil
 deal. Once it’s gone,
 it’s really gone.
Fetching and updating
individual attributes
                             >> user = User.find(2)

Rails will let you fetch a   => #<User id: 2, name: "Strom",
                                              age: 15>
specific attribute of an      >> user.name
                             => "Strom"
object                       >> user.name = "Storm"
                             => "Storm"

it will also let you         >> user.save
                             => true
manipulate that single       >> user = User.find(2)
                             => #<User id: 2, name: "Storm",
attribute                                     age: 15>
Model Objects

                id   Name    Age



                1    Gypsy   12



                2    Storm   14
Model Objects        users = User.all




                id      Name            Age



                1       Gypsy           12



                2       Storm           14
Model Objects                                   users = User.all




                                               id      Name            Age


user = User.first(:conditions => 'age > 12')   1       Gypsy           12



                                               2       Storm           14
Model Objects                                   users = User.all




                                               id      Name            Age


user = User.first(:conditions => 'age > 12')   1       Gypsy           12


         user = User.find_by_name("Storm")     2       Storm           14
class User < ActiveRecord::Base




      ###################
      ### Validations ###
      ###################

      validates_presence_of   :name
      validates_uniqueness_of :name




end


Validations
Putting rules on the way your data should
behave in Rails
Validation Power
Validation Power

Adding validations ensures you get the data you are
expecting
Validation Power

Adding validations ensures you get the data you are
expecting
Enforces certain rules and expectations so you can
count on them later
Validation Power

Adding validations ensures you get the data you are
expecting
Enforces certain rules and expectations so you can
count on them later
Rails has several predefined validations
Validation Power

Adding validations ensures you get the data you are
expecting
Enforces certain rules and expectations so you can
count on them later
Rails has several predefined validations
  validates_uniqueness_of, validates_presence_of,
  validates_numericality_of, validates_format_of, etc
validates_format_of :email,
                    :with => /A[^s@]+@[^s@]+.[^s@]+z/,
                    :message => "is not a valid address"




validates_presence_of   :name, :age




Always call the type of validation followed by the
method or methods and any additional rules,
such as formatting and messages
Custom Validations


                        validate :age_must_be_less_than_30
You can also define
                        def age_must_be_less_than_30
your own rules. Just      if age > 30
                            errors.add_to_base("Age must be
call validate and the                         less than 30")
name of the method        end
                        end
>>   user = User.new(:name => "Tipper", :age => 45)
 =>   #<User id: nil, name: "Tipper", age: 45>
 >>   user.save
 =>   false
 >>   user.errors.full_messages
 =>   ["Age must be less than 30"]




Validation explosion
When a record won’t save, calling
errors.full_messages will show you what went wrong
Questions?
Starting a Database Lab
Your book has instructions for building your first
models with validations and creating some data

More Related Content

What's hot

RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
Suyeol Jeon
 
jQuery
jQueryjQuery
jQuery
Jon Erickson
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
Christian Baranowski
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
Mohammed El Rafie Tarabay
 
Storing tree structures with MongoDB
Storing tree structures with MongoDBStoring tree structures with MongoDB
Storing tree structures with MongoDB
Vyacheslav
 
The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210
Mahmoud Samir Fayed
 
Automating Drupal Migrations
Automating Drupal MigrationsAutomating Drupal Migrations
Automating Drupal Migrations
littleMAS
 
Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3
Markus Klems
 
David Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order componentsDavid Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order components
OdessaJS Conf
 
Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Mongo db mug_2012-02-07
Mongo db mug_2012-02-07
Will Button
 
Simple Photo Processing and Web Display with Perl
Simple Photo Processing and Web Display with PerlSimple Photo Processing and Web Display with Perl
Simple Photo Processing and Web Display with Perl
Kent Cowgill
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Suyeol Jeon
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
Julie Iskander
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
rogerbodamer
 
Scaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkitScaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkit
Bojan Babic
 
The world's next top data model
The world's next top data modelThe world's next top data model
The world's next top data model
Patrick McFadin
 
G3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy AnnotationsG3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy Annotations
Iván López Martín
 
groovy databases
groovy databasesgroovy databases
groovy databases
Paul King
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
Sten Anderson
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 

What's hot (20)

RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
jQuery
jQueryjQuery
jQuery
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
Storing tree structures with MongoDB
Storing tree structures with MongoDBStoring tree structures with MongoDB
Storing tree structures with MongoDB
 
The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210
 
Automating Drupal Migrations
Automating Drupal MigrationsAutomating Drupal Migrations
Automating Drupal Migrations
 
Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3
 
David Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order componentsDavid Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order components
 
Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Mongo db mug_2012-02-07
Mongo db mug_2012-02-07
 
Simple Photo Processing and Web Display with Perl
Simple Photo Processing and Web Display with PerlSimple Photo Processing and Web Display with Perl
Simple Photo Processing and Web Display with Perl
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
 
Scaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkitScaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkit
 
The world's next top data model
The world's next top data modelThe world's next top data model
The world's next top data model
 
G3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy AnnotationsG3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy Annotations
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 

Viewers also liked

ActiveRecord Associations (1), Season 1
ActiveRecord Associations (1), Season 1ActiveRecord Associations (1), Season 1
ActiveRecord Associations (1), Season 1
RORLAB
 
Rails Database Migrations - RORLab Season 3-3
Rails Database Migrations - RORLab Season 3-3Rails Database Migrations - RORLab Season 3-3
Rails Database Migrations - RORLab Season 3-3
창훈 정
 
Associations in Rails
Associations in RailsAssociations in Rails
Associations in Rails
James Gray
 
Being in a State of REST
Being in a State of RESTBeing in a State of REST
Being in a State of REST
Aslam Khan
 
Wadid Erian 25 Aug 5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)
Wadid Erian 25 Aug  5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)Wadid Erian 25 Aug  5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)
Wadid Erian 25 Aug 5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)
Global Risk Forum GRFDavos
 
Mobile Marketing
Mobile MarketingMobile Marketing
Mobile Marketing
MarcusThomasLLC
 
Niagara falls frozen year-1911
Niagara falls frozen   year-1911Niagara falls frozen   year-1911
Niagara falls frozen year-1911
Samuel Lima
 

Viewers also liked (7)

ActiveRecord Associations (1), Season 1
ActiveRecord Associations (1), Season 1ActiveRecord Associations (1), Season 1
ActiveRecord Associations (1), Season 1
 
Rails Database Migrations - RORLab Season 3-3
Rails Database Migrations - RORLab Season 3-3Rails Database Migrations - RORLab Season 3-3
Rails Database Migrations - RORLab Season 3-3
 
Associations in Rails
Associations in RailsAssociations in Rails
Associations in Rails
 
Being in a State of REST
Being in a State of RESTBeing in a State of REST
Being in a State of REST
 
Wadid Erian 25 Aug 5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)
Wadid Erian 25 Aug  5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)Wadid Erian 25 Aug  5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)
Wadid Erian 25 Aug 5 00 _ Syria-Drought Risk & Resilience_ IDRC14 (1)
 
Mobile Marketing
Mobile MarketingMobile Marketing
Mobile Marketing
 
Niagara falls frozen year-1911
Niagara falls frozen   year-1911Niagara falls frozen   year-1911
Niagara falls frozen year-1911
 

Similar to Rails Model Basics

RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
Dr Nic Williams
 
Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)
Joao Lucas Santana
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
Allie Jones
 
Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in Rails
Sandip Ransing
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
rstankov
 
Windows power shell and active directory
Windows power shell and active directoryWindows power shell and active directory
Windows power shell and active directory
Dan Morrill
 
DataMapper
DataMapperDataMapper
DataMapper
Yehuda Katz
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
Jens-Christian Fischer
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Juliana Lucena
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
Mykyta Protsenko
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
Solution4Future
 
Migrating legacy data
Migrating legacy dataMigrating legacy data
Migrating legacy data
Patrick Huesler
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
shaokun
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
Michael Mahlberg
 
Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)
Sergio Gomez Villamor
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
Gabriele Lana
 
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
Artificial Intelligence Institute at UofSC
 

Similar to Rails Model Basics (20)

RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 
Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in Rails
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Windows power shell and active directory
Windows power shell and active directoryWindows power shell and active directory
Windows power shell and active directory
 
DataMapper
DataMapperDataMapper
DataMapper
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Migrating legacy data
Migrating legacy dataMigrating legacy data
Migrating legacy data
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
 
Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
 

More from James Gray

A Dickens of A Keynote
A Dickens of A KeynoteA Dickens of A Keynote
A Dickens of A Keynote
James Gray
 
I Doubt That!
I Doubt That!I Doubt That!
I Doubt That!
James Gray
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
James Gray
 
Counting on God
Counting on GodCounting on God
Counting on God
James Gray
 
In the Back of Your Mind
In the Back of Your MindIn the Back of Your Mind
In the Back of Your Mind
James Gray
 
Unblocked
UnblockedUnblocked
Unblocked
James Gray
 
Module Magic
Module MagicModule Magic
Module Magic
James Gray
 
API Design
API DesignAPI Design
API Design
James Gray
 
Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)
James Gray
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
James Gray
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in Rails
James Gray
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And Rendering
James Gray
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
James Gray
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and Controllers
James Gray
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails Interface
James Gray
 
Ruby
RubyRuby
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on Rails
James Gray
 

More from James Gray (17)

A Dickens of A Keynote
A Dickens of A KeynoteA Dickens of A Keynote
A Dickens of A Keynote
 
I Doubt That!
I Doubt That!I Doubt That!
I Doubt That!
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Counting on God
Counting on GodCounting on God
Counting on God
 
In the Back of Your Mind
In the Back of Your MindIn the Back of Your Mind
In the Back of Your Mind
 
Unblocked
UnblockedUnblocked
Unblocked
 
Module Magic
Module MagicModule Magic
Module Magic
 
API Design
API DesignAPI Design
API Design
 
Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in Rails
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And Rendering
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and Controllers
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails Interface
 
Ruby
RubyRuby
Ruby
 
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on Rails
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 

Rails Model Basics

  • 2. What is a Model? It’s a Ruby Object Home of your business logic and object rules ActiveRecord The layer in Rails that talks to the database Gives you a lot of conventional tools to make manipulating data easy Home of CRUD create, read, update and delete
  • 3. Think Model - Think Table id Name Age 1 Gypsy 12 2 Storm 14
  • 4. Think Model - Think Table The Model as a whole id Name Age is an object Calling a method on the model effects all data in the model 1 Gypsy 12 2 Storm 14
  • 5. Think Model - Think Table The Model as a whole id Name Age is an object Calling a method on the model effects all data in the model 1 Gypsy 12 A record in the model is also an object Calling a method on a record 2 Storm 14 effects only that record
  • 6.
  • 8. How do I get one? Easy! Become one with ruby script/generate in your console!
  • 9. Tell the generate command what you How do I want to generate and get one? you can even add in fields. Easy! Become one with $ ruby script/generate model user name:string ruby script/generate address:string age:integer admin:boolean in your console!
  • 10. class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name t.integer :age t.string :address t.boolean :admin t.timestamps end end def self.down drop_table :users end end What happens after generate? Rails creates a file representing the new model you just created called a migration.
  • 11. class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name t.integer :age t.string :address t.boolean :admin t.timestamps end end def self.down drop_table :users end end What happens after generate? Rails creates a file representing the new model you just created called a migration.
  • 13. Magic Fields Rails adds a few magic fields to your model
  • 14. Magic Fields Rails adds a few magic fields to your model id - this is the record’s unique id. Every model has one, even though it doesn’t appear in the migration
  • 15. Magic Fields Rails adds a few magic fields to your model id - this is the record’s unique id. Every model has one, even though it doesn’t appear in the migration timestamps
  • 16. Magic Fields Rails adds a few magic fields to your model id - this is the record’s unique id. Every model has one, even though it doesn’t appear in the migration timestamps created_at - puts a time stamp when a new record is created
  • 17. Magic Fields Rails adds a few magic fields to your model id - this is the record’s unique id. Every model has one, even though it doesn’t appear in the migration timestamps created_at - puts a time stamp when a new record is created updated_at - puts a time stamp when a record is changed
  • 18. So I have this migration. Now what? Generating the model is half the battle Now you have to tie it into the Rails infrastructure How? Why, run a rake task, of course!
  • 19. Rake
  • 20. Rake Infrastructure that helps you run common tasks in Rails easily. migrations, run tests and many more
  • 21. Rake Infrastructure that helps you run common tasks in Rails easily. migrations, run tests and many more Completely customizable - create your own rake tasks
  • 22. Rake Infrastructure that helps For a list of all the rake you run common tasks commands, just run in Rails easily. $ rake -T migrations, run tests and many more Completely customizable - create your own rake tasks
  • 23. Rake Infrastructure that helps For a list of all the rake you run common tasks commands, just run in Rails easily. $ rake -T migrations, run tests To execute your and many more beautifully crafted Completely customizable migration, just run - create your own rake tasks $ rake db:migrate
  • 24. A bit more about Migrations $ script/generate migration add_email_to_users add_column() takes the model name, field name and data type class AddEmailToUsers < ActiveRecord::Migration def self.up add_column :users, :email, :string self.down will revert to end the pre-migrated state def self.down remove_column :users, :email end use the same rake end db:migrate to execute command
  • 25. ActiveRecord::Schema.define(:version => 20100301045108) do create_table "users", :force => true do |t| t.string "name" t.integer "age" t.string "address" t.boolean "admin" t.datetime "created_at" t.datetime "updated_at" end end Meet the Schema file Rails generates a ‘map’ of your database.This is the map after the initial model generation
  • 26. create_table "users", :force => true do |t| t.string "name" t.integer "age" t.string "address" t.boolean "admin" t.datetime "created_at" t.datetime "updated_at" t.string "email" end Schema after migration Each migration updates and replaces the existing schema
  • 27. create_table "users", :force => true do |t| t.string "name" t.integer "age" t.string "address" t.boolean "admin" t.datetime "created_at" t.datetime "updated_at" t.string "email" end Schema after migration Each migration updates and replaces the existing schema
  • 28. Let’s play with some CRUD
  • 29. Let’s play with some CRUD CRUD stands for Create, Read, Update and Delete
  • 30. Let’s play with some CRUD CRUD stands for Create, Read, Update and Delete These are the heart of ActiveRecord and the primary purpose of the model
  • 31. Let’s play with some CRUD CRUD stands for Create, Read, Update and Delete These are the heart of ActiveRecord and the primary purpose of the model Between these four actions, you can accomplish pretty much anything in your database
  • 32. C is for Create
  • 33. C is for Create Create - adds an object to the database
  • 34. C is for Create Create - adds an object to the database user = User.new(:name => "Gypsy", Two common ways of :age => 12) user.save achieving this are with new() and save() or create()
  • 35. C is for Create Create - adds an object to the database user = User.new(:name => "Gypsy", Two common ways of :age => 12) user.save achieving this are with new() and save() or user = User.create(:name => "Storm", create() :age => 14) create() is a combined new() and save()
  • 36. R is for Read Read - Retrieves an object from the user = User.find(1) # by id database => #<User id: 1, name: "Gypsy", age: 12> user = User.first # first record You can find virtually => #<User id: 1, name: "Gypsy", age: 12> anything using user = User.last # last record => #<User id: 2, name: "Storm", age: 14> ActiveRecords find methods
  • 37. Some more Read methods user = User.find_by_name("Storm") You can pass in => #<User id: 2, name: "Storm", age: 14, > arguments to find_by() users = User.all # returns an array of all users => [#<User id: 1, name: "Gypsy", age: 12>, #<User id: 2, name: "Storm", age: 14>] You an also use SQL to user = User.all(:order => 'age DESC') => [#<User id: 2, name: "Storm", age: 14>, locate data within #<User id: 1, name: "Gypsy", age: 12>] specific criteria user = User.first(:conditions => 'age > 12') => #<User id: 2, name: "Storm", age: 14>
  • 38. U is for Update Update - saves existing object with new data user.update_attributes( :age => 15, update_attributes() => true :email => "storm@gmail.com") takes in a Hash of => #<User id: 2, name: "Storm", age: 15, email: "storm@gmail.com"> attributes and saves them to the database
  • 39. D is for Delete Delete - removes object from database user = User.find_by_name("Gypsy") user.destroy This is an all or nothing User.find_by_name("Gypsy") => nil deal. Once it’s gone, it’s really gone.
  • 40. Fetching and updating individual attributes >> user = User.find(2) Rails will let you fetch a => #<User id: 2, name: "Strom", age: 15> specific attribute of an >> user.name => "Strom" object >> user.name = "Storm" => "Storm" it will also let you >> user.save => true manipulate that single >> user = User.find(2) => #<User id: 2, name: "Storm", attribute age: 15>
  • 41. Model Objects id Name Age 1 Gypsy 12 2 Storm 14
  • 42. Model Objects users = User.all id Name Age 1 Gypsy 12 2 Storm 14
  • 43. Model Objects users = User.all id Name Age user = User.first(:conditions => 'age > 12') 1 Gypsy 12 2 Storm 14
  • 44. Model Objects users = User.all id Name Age user = User.first(:conditions => 'age > 12') 1 Gypsy 12 user = User.find_by_name("Storm") 2 Storm 14
  • 45. class User < ActiveRecord::Base ################### ### Validations ### ################### validates_presence_of :name validates_uniqueness_of :name end Validations Putting rules on the way your data should behave in Rails
  • 47. Validation Power Adding validations ensures you get the data you are expecting
  • 48. Validation Power Adding validations ensures you get the data you are expecting Enforces certain rules and expectations so you can count on them later
  • 49. Validation Power Adding validations ensures you get the data you are expecting Enforces certain rules and expectations so you can count on them later Rails has several predefined validations
  • 50. Validation Power Adding validations ensures you get the data you are expecting Enforces certain rules and expectations so you can count on them later Rails has several predefined validations validates_uniqueness_of, validates_presence_of, validates_numericality_of, validates_format_of, etc
  • 51. validates_format_of :email, :with => /A[^s@]+@[^s@]+.[^s@]+z/, :message => "is not a valid address" validates_presence_of :name, :age Always call the type of validation followed by the method or methods and any additional rules, such as formatting and messages
  • 52. Custom Validations validate :age_must_be_less_than_30 You can also define def age_must_be_less_than_30 your own rules. Just if age > 30 errors.add_to_base("Age must be call validate and the less than 30") name of the method end end
  • 53. >> user = User.new(:name => "Tipper", :age => 45) => #<User id: nil, name: "Tipper", age: 45> >> user.save => false >> user.errors.full_messages => ["Age must be less than 30"] Validation explosion When a record won’t save, calling errors.full_messages will show you what went wrong
  • 55. Starting a Database Lab Your book has instructions for building your first models with validations and creating some data

Editor's Notes