Active Record Models map an object’s attributes to columns in a relational database.
The Active Record Pattern is a pattern that maps:
- Classes to tables
- Objects to rows of data within that table
- Getters/Setters to columns in that table
Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.
- Foreign keys – These fields should be named following the pattern
singularized_table_name_id(e.g.,item_id,order_id). These are the fields that Active Record will look for when you create associations between your models. - Primary keys – By default, Active Record will use an integer column named
idas the table’s primary key. When using Active Record Migrations to create your tables, this column will be automatically created.
This is how it works.
By default the model looks for a lower case plural name of the model
users database table:
| id | username | |
|---|---|---|
| 1 | joe | joe@yahoo.com |
| 2 | bob | bob@apple.com |
| 3 | jon | jon@yahoo.com |
user.rb ActiveRecord model:
# ActiveRecord model
class User < ActiveRecord:Base
end
When we instantiate a user object, we automatically have getters and setters for all columns.
Now run these in the rails console …
# Creates an in memory User object:
user = User.new(username: 'bill')
These methods save to the database:
user.save
user = User.create(username: 'rick')
Retrieve column values:
user = User.find_by username: 'joe'
user.email
users = User.where(username: 'joe')