2023-05-08 - Active Record


main topics


Active Record

From RoR docs:

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Link to the "Active Record Pattern" article by Martin Fowler.

rake

# show all tasks
rake -T

# load the app config inside an irb session
rake console

Migrations

Each time you change your schema (add/remove table/column) you need to create a schema migration.

It's a change in the structure of your schema, not the data.

Important

  • The first part of a migration file MUST be timestamp!
  • The name after the timestamp SHOULD precisely describe what's happening in the migration.

Example

timestamp="$(date +'%Y%m%d%H%M%S')"

# as restaurants is in plural, it's implicit
# that it's a table.
db/migrate/${timestamp}_create_restaurants.rb

contents of the *_create_restaurants.rb:

class CreateRestaurants < ActiveRecord::Migration[7.0]
  def change
    create_table :restaurants do |t|
      t.string :name
      t.string :address
      t.timestamps # for created_at and updated_at
    end
  end
end

Notes about conventions for migrations:

PAREI em 28min!!

Naming conventions

pluralization is handled beautifully by Active Record.

Sequence

Validation

uniqueness