Skip to the workspace
Pebellslearn by building
Models  ›  Lesson

Creating Models, Migrations and Data Types

Creating Models 15 minA model is a Ruby class backed by a table; migrations create and change that table step by step, and each column has a type such as string, text, integer, decimal, boolean, date or datetime.

ruby on rails / Creating Models, Migrations and Data Types

Explore each scene at your own pace.

01 · The rule

The rule

Creating Models, Migrations and Data Types

Bookclub needs to remember books. In Rails that means two things that always travel together: a table in the database and a model class that reads and writes it. Migrations are how the table comes into being and how it changes over time.

The rule

One model, one table; change the table only through migrations.

bin/rails generate model Book title:string author:string pages:integer \
  price:decimal published_on:date available:boolean

This writes app/models/book.rb:

class Book < ApplicationRecord
end

and a migration in db/migrate/:

class CreateBooks < ActiveRecord::Migration[8.0]
  def change
    create_table :books do |t|
      t.string  :title
      t.string  :author
      t.integer :pages
      t.decimal :price, precision: 8, scale: 2   # precision and scale added by hand
      t.date    :published_on
      t.boolean :available, default: true        # default added by hand
      t.timestamps                               # created_at, updated_at
    end
  end
end

bin/rails db:migrate runs it. Rails adds an id primary key automatically, and t.timestamps adds created_at and updated_at, which Rails fills in for you. The empty class already knows every column: Book.new(title: "Dune").title works because Active Record reads the table.

Naming is by convention: model Book (singular, CamelCase) ↔ table books (plural, snake_case).

Common data types:

Type Use for
string short text: titles, names, emails
text long text: review bodies
integer whole numbers: pages, ratings
decimal exact numbers: money
float approximate numbers: measurements
boolean yes or no
date / datetime a day / a moment
references a foreign key such as book_id

Later changes are new migrations: bin/rails g migration AddIsbnToBooks isbn:string. bin/rails db:rollback undoes the last one.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.