• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Rails Model Basics
 

Rails Model Basics

on

  • 4,141 views

This was the third speech of a three day Rails training I gave in Tulsa, OK in the spring 2010.

This was the third speech of a three day Rails training I gave in Tulsa, OK in the spring 2010.

Statistics

Views

Total Views
4,141
Views on SlideShare
4,124
Embed Views
17

Actions

Likes
3
Downloads
33
Comments
0

3 Embeds 17

http://www.slideshare.net 15
http://webcache.googleusercontent.com 1
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />

Rails Model Basics Rails Model Basics Presentation Transcript

  • 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