SlideShare uma empresa Scribd logo
1 de 55
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

Mais conteúdo relacionado

Mais procurados

RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
Storing tree structures with MongoDB
Storing tree structures with MongoDBStoring tree structures with MongoDB
Storing tree structures with MongoDBVyacheslav
 
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 210Mahmoud Samir Fayed
 
Automating Drupal Migrations
Automating Drupal MigrationsAutomating Drupal Migrations
Automating Drupal MigrationslittleMAS
 
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 CQL3Markus 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 componentsOdessaJS Conf
 
Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Will 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 PerlKent Cowgill
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
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 toolkitBojan 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 modelPatrick 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 AnnotationsIván López Martín
 
groovy databases
groovy databasesgroovy databases
groovy databasesPaul King
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with GroovySten 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
 

Mais procurados (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! 
 

Destaque

ActiveRecord Associations (1), Season 1
ActiveRecord Associations (1), Season 1ActiveRecord Associations (1), Season 1
ActiveRecord Associations (1), Season 1RORLAB
 
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 RailsJames Gray
 
Being in a State of REST
Being in a State of RESTBeing in a State of REST
Being in a State of RESTAslam 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
 
Niagara falls frozen year-1911
Niagara falls frozen   year-1911Niagara falls frozen   year-1911
Niagara falls frozen year-1911Samuel Lima
 

Destaque (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
 

Semelhante a Rails Model Basics

RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteDr 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 8Allie Jones
 
Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in RailsSandip Ransing
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Windows power shell and active directory
Windows power shell and active directoryWindows power shell and active directory
Windows power shell and active directoryDan Morrill
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan 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 MapperJonathan 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 OpsMykyta Protsenko
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
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 DeveloperJon Kruger
 

Semelhante a 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
 

Mais de James Gray

A Dickens of A Keynote
A Dickens of A KeynoteA Dickens of A Keynote
A Dickens of A KeynoteJames Gray
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsJames Gray
 
Counting on God
Counting on GodCounting on God
Counting on GodJames Gray
 
In the Back of Your Mind
In the Back of Your MindIn the Back of Your Mind
In the Back of Your MindJames 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 GitHubJames Gray
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in RailsJames Gray
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And RenderingJames Gray
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with RailsJames Gray
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersJames Gray
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails InterfaceJames Gray
 
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on RailsJames Gray
 

Mais de 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
 

Último

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Último (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

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

Notas do Editor