Rails Model Basics

3,715 views

Published on

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

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,715
On SlideShare
0
From Embeds
0
Number of Embeds
19
Actions
Shares
0
Downloads
38
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide


























































  • Rails Model Basics

    1. 1. Model Basics Business Logic Goes Here
    2. 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. 3. Think Model - Think Table id Name Age 1 Gypsy 12 2 Storm 14
    4. 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. 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. 6. How do I get one?
    7. 7. How do I get one? Easy! Become one with ruby script/generate in your console!
    8. 8. 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!
    9. 9. 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.
    10. 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. 11. Magic Fields
    12. 12. Magic Fields Rails adds a few magic fields to your model
    13. 13. 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
    14. 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 timestamps
    15. 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 created_at - puts a time stamp when a new record is created
    16. 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 updated_at - puts a time stamp when a record is changed
    17. 17. 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!
    18. 18. Rake
    19. 19. Rake Infrastructure that helps you run common tasks in Rails easily. migrations, run tests and many more
    20. 20. Rake Infrastructure that helps you run common tasks in Rails easily. migrations, run tests and many more Completely customizable - create your own rake tasks
    21. 21. 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
    22. 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 To execute your and many more beautifully crafted Completely customizable migration, just run - create your own rake tasks $ rake db:migrate
    23. 23. 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
    24. 24. 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
    25. 25. 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
    26. 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. 27. Let’s play with some CRUD
    28. 28. Let’s play with some CRUD CRUD stands for Create, Read, Update and Delete
    29. 29. 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
    30. 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 Between these four actions, you can accomplish pretty much anything in your database
    31. 31. C is for Create
    32. 32. C is for Create Create - adds an object to the database
    33. 33. 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()
    34. 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 user = User.create(:name => "Storm", create() :age => 14) create() is a combined new() and save()
    35. 35. 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
    36. 36. 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>
    37. 37. 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
    38. 38. 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.
    39. 39. 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>
    40. 40. Model Objects id Name Age 1 Gypsy 12 2 Storm 14
    41. 41. Model Objects users = User.all id Name Age 1 Gypsy 12 2 Storm 14
    42. 42. Model Objects users = User.all id Name Age user = User.first(:conditions => 'age > 12') 1 Gypsy 12 2 Storm 14
    43. 43. 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
    44. 44. 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
    45. 45. Validation Power
    46. 46. Validation Power Adding validations ensures you get the data you are expecting
    47. 47. Validation Power Adding validations ensures you get the data you are expecting Enforces certain rules and expectations so you can count on them later
    48. 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 Rails has several predefined validations
    49. 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 validates_uniqueness_of, validates_presence_of, validates_numericality_of, validates_format_of, etc
    50. 50. 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
    51. 51. 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
    52. 52. >> 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
    53. 53. Questions?
    54. 54. Starting a Database Lab Your book has instructions for building your first models with validations and creating some data

    ×