2023-05-08 - Active Record
main topics
- Active Record
- some details about rake
rake -T
is your friend :)
- Migrations
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.
- 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:
- the filename is in lower_snake_case
- the class name is in CapitalizedCamelCase
- in the example above we're creating a table, therefore it's going to be in plural (when a migration refers to a column, it's not written in plural).
PAREI em 28min!!
Naming conventions
- table
- model
- class
pluralization is handled beautifully by Active Record.
Sequence
- draw table in db.lewagon.com
- write the migration files
- run
rake db:migrate
- write the models
Validation
uniqueness
- Use
unique: true
in the migration column configuration - Use
uniqueness: true
in the modelvalidates
configuration