2015-01-14 01:22:13 -05:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
2014-12-23 17:32:50 -05:00
2012-09-01 17:25:58 -04:00
Active Record Basics
====================
2013-04-03 07:18:20 -04:00
2012-11-29 17:25:02 -05:00
This guide is an introduction to Active Record.
After reading this guide, you will know:
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
* What Object Relational Mapping and Active Record are and how they are used in
2012-12-12 12:40:51 -05:00
Rails.
2012-11-29 08:14:08 -05:00
* How Active Record fits into the Model-View-Controller paradigm.
2013-04-03 07:18:20 -04:00
* How to use Active Record models to manipulate data stored in a relational
2012-12-12 12:40:51 -05:00
database.
2012-11-29 08:14:08 -05:00
* Active Record schema naming conventions.
* The concepts of database migrations, validations and callbacks.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
--------------------------------------------------------------------------------
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
What is Active Record?
----------------------
2009-02-05 20:57:02 -05:00
2015-03-15 11:10:48 -04:00
Active Record is the M in [MVC ](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller ) - the
2013-04-03 07:18:20 -04:00
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
2012-12-12 12:40:51 -05:00
Object Relational Mapping system.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### The Active Record Pattern
2009-02-05 20:57:02 -05:00
2013-04-03 07:19:20 -04:00
[Active Record was described by Martin Fowler ](http://www.martinfowler.com/eaaCatalog/activeRecord.html )
in his book _Patterns of Enterprise Application Architecture_ . In
Active Record, objects carry both persistent data and behavior which
operates on that data. Active Record takes the opinion that ensuring
2014-10-24 18:01:05 -04:00
data access logic as part of the object will educate users of that
2012-12-12 12:40:51 -05:00
object on how to write to and read from the database.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Object Relational Mapping
2009-02-05 20:57:02 -05:00
2015-02-23 10:39:59 -05:00
Object Relational Mapping, commonly referred to as its abbreviation ORM, is
2013-04-03 07:18:20 -04:00
a technique that connects the rich objects of an application to tables in
a relational database management system. Using ORM, the properties and
relationships of the objects in an application can be easily stored and
retrieved from a database without writing SQL statements directly and with less
2012-12-12 12:40:51 -05:00
overall database access code.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Active Record as an ORM Framework
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
Active Record gives us several mechanisms, the most important being the ability
2012-12-12 12:40:51 -05:00
to:
2009-02-05 20:57:02 -05:00
2013-09-26 03:26:03 -04:00
* Represent models and their data.
* Represent associations between these models.
* Represent inheritance hierarchies through related models.
* Validate models before they get persisted to the database.
2009-02-05 20:57:02 -05:00
* Perform database operations in an object-oriented fashion.
2012-09-01 17:25:58 -04:00
Convention over Configuration in Active Record
----------------------------------------------
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
When writing applications using other programming languages or frameworks, it
may be necessary to write a lot of configuration code. This is particularly true
for ORM frameworks in general. However, if you follow the conventions adopted by
2015-01-12 00:38:10 -05:00
Rails, you'll need to write very little configuration (in some cases no
2013-04-03 07:18:20 -04:00
configuration at all) when creating Active Record models. The idea is that if
2013-05-31 20:21:36 -04:00
you configure your applications in the very same way most of the time then this
should be the default way. Thus, explicit configuration would be needed
2013-06-06 08:29:01 -04:00
only in those cases where you can't follow the standard convention.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Naming Conventions
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
By default, Active Record uses some naming conventions to find out how the
mapping between models and database tables should be created. Rails will
pluralize your class names to find the respective database table. So, for
a class `Book` , you should have a database table called **books** . The Rails
pluralization mechanisms are very powerful, being capable to pluralize (and
singularize) both regular and irregular words. When using class names composed
of two or more words, the model class name should follow the Ruby conventions,
using the CamelCase form, while the table name must contain the words separated
2012-12-12 12:40:51 -05:00
by underscores. Examples:
2009-02-05 20:57:02 -05:00
2013-09-26 03:26:03 -04:00
* Database Table - Plural with underscores separating words (e.g., `book_clubs` ).
2013-04-03 07:18:20 -04:00
* Model Class - Singular with the first letter of each word capitalized (e.g.,
2013-09-26 03:26:03 -04:00
`BookClub` ).
2009-02-05 20:57:02 -05:00
2014-05-21 21:47:18 -04:00
| Model / Class | Table / Schema |
| ---------------- | -------------- |
| `Article` | `articles` |
| `LineItem` | `line_items` |
| `Deer` | `deers` |
| `Mouse` | `mice` |
| `Person` | `people` |
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Schema Conventions
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
Active Record uses naming conventions for the columns in database tables,
2012-12-12 12:40:51 -05:00
depending on the purpose of these columns.
2013-04-03 07:18:20 -04:00
* **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
2012-12-12 12:40:51 -05:00
your models.
2013-04-03 07:18:20 -04:00
* **Primary keys** - By default, Active Record will use an integer column named
2013-09-26 03:26:03 -04:00
`id` as the table's primary key. When using [Active Record
2013-04-03 07:18:20 -04:00
Migrations](migrations.html) to create your tables, this column will be
2012-12-12 12:40:51 -05:00
automatically created.
2013-07-08 06:37:45 -04:00
There are also some optional column names that will add additional features
2012-12-12 12:40:51 -05:00
to Active Record instances:
2013-04-03 07:18:20 -04:00
* `created_at` - Automatically gets set to the current date and time when the
2012-12-12 12:40:51 -05:00
record is first created.
2013-04-03 07:18:20 -04:00
* `updated_at` - Automatically gets set to the current date and time whenever
2012-12-12 12:40:51 -05:00
the record is updated.
2013-04-03 07:18:20 -04:00
* `lock_version` - Adds [optimistic
locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to
2012-12-12 12:40:51 -05:00
a model.
2013-04-03 07:18:20 -04:00
* `type` - Specifies that the model uses [Single Table
2014-09-30 11:01:15 -04:00
Inheritance](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance).
2013-04-03 07:36:30 -04:00
* `(association_name)_type` - Stores the type for
[polymorphic associations ](association_basics.html#polymorphic-associations ).
2013-04-03 07:18:20 -04:00
* `(table_name)_count` - Used to cache the number of belonging objects on
2015-03-18 03:03:05 -04:00
associations. For example, a `comments_count` column in an `Article` class that
2013-04-03 07:18:20 -04:00
has many instances of `Comment` will cache the number of existent comments
2014-05-21 21:47:18 -04:00
for each article.
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, `type` is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Creating Active Record Models
-----------------------------
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
It is very easy to create Active Record models. All you have to do is to
2012-12-12 12:40:51 -05:00
subclass the `ActiveRecord::Base` class and you're good to go:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2011-10-03 09:47:24 -04:00
class Product < ActiveRecord::Base
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
This will create a `Product` model, mapped to a `products` table at the
database. By doing this you'll also have the ability to map the columns of each
row in that table with the attributes of the instances of your model. Suppose
2012-12-12 12:40:51 -05:00
that the `products` table was created using an SQL sentence like:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```sql
2009-02-05 20:57:02 -05:00
CREATE TABLE products (
id int(11) NOT NULL auto_increment,
name varchar(255),
PRIMARY KEY (id)
);
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
Following the table schema above, you would be able to write code like the
2012-12-12 12:40:51 -05:00
following:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2009-02-05 20:57:02 -05:00
p = Product.new
p.name = "Some Book"
puts p.name # "Some Book"
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Overriding the Naming Conventions
---------------------------------
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
What if you need to follow a different naming convention or need to use your
Rails application with a legacy database? No problem, you can easily override
2012-12-12 12:40:51 -05:00
the default conventions.
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
You can use the `ActiveRecord::Base.table_name=` method to specify the table
2012-12-12 12:40:51 -05:00
name that should be used:
2010-06-14 18:11:35 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2009-02-05 20:57:02 -05:00
class Product < ActiveRecord::Base
2011-11-29 07:28:04 -05:00
self.table_name = "PRODUCT"
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2010-06-14 18:11:35 -04:00
2013-04-03 07:18:20 -04:00
If you do so, you will have to define manually the class name that is hosting
the fixtures (class_name.yml) using the `set_fixture_class` method in your test
2012-12-12 12:40:51 -05:00
definition:
2010-06-14 18:11:35 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2010-04-08 12:05:12 -04:00
class FunnyJoke < ActiveSupport::TestCase
2013-08-24 04:11:18 -04:00
set_fixture_class funny_jokes: Joke
2010-04-08 12:05:12 -04:00
fixtures :funny_jokes
...
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
It's also possible to override the column that should be used as the table's
2013-08-20 22:54:27 -04:00
primary key using the `ActiveRecord::Base.primary_key=` method:
2010-06-14 18:11:35 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2009-02-05 20:57:02 -05:00
class Product < ActiveRecord::Base
2013-08-20 22:54:27 -04:00
self.primary_key = "product_id"
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
CRUD: Reading and Writing Data
------------------------------
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
CRUD is an acronym for the four verbs we use to operate on data: **C**reate,
**R**ead, **U**pdate and **D**elete. Active Record automatically creates methods
2012-12-12 12:40:51 -05:00
to allow an application to read and manipulate data stored within its tables.
2009-08-13 12:02:01 -04:00
2012-09-01 17:25:58 -04:00
### Create
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
Active Record objects can be created from a hash, a block or have their
attributes manually set after creation. The `new` method will return a new
2012-12-12 12:40:51 -05:00
object while `create` will return the object and save it to the database.
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
For example, given a model `User` with attributes of `name` and `occupation` ,
2012-12-12 12:40:51 -05:00
the `create` method call will create and save a new record into the database:
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-12-04 16:50:27 -05:00
user = User.create(name: "David", occupation: "Code Artist")
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-12-12 12:40:51 -05:00
Using the `new` method, an object can be instantiated without being saved:
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-12-04 16:50:27 -05:00
user = User.new
user.name = "David"
user.occupation = "Code Artist"
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-09-01 21:37:59 -04:00
A call to `user.save` will commit the record to the database.
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
Finally, if a block is provided, both `create` and `new` will yield the new
2012-12-12 12:40:51 -05:00
object to that block for initialization:
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-12-04 16:50:27 -05:00
user = User.new do |u|
u.name = "David"
u.occupation = "Code Artist"
end
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-09-01 17:25:58 -04:00
### Read
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
Active Record provides a rich API for accessing data within a database. Below
2012-12-12 12:40:51 -05:00
are a few examples of different data access methods provided by Active Record.
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2013-01-03 19:26:32 -05:00
# return a collection with all users
2012-12-04 16:50:27 -05:00
users = User.all
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2013-01-03 19:26:32 -05:00
# return the first user
2012-12-04 16:50:27 -05:00
user = User.first
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-12-04 16:50:27 -05:00
# return the first user named David
2013-06-30 19:38:46 -04:00
david = User.find_by(name: 'David')
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-12-04 16:50:27 -05:00
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
You can learn more about querying an Active Record model in the [Active Record
2012-12-12 12:40:51 -05:00
Query Interface](active_record_querying.html) guide.
2009-08-13 12:02:01 -04:00
2012-09-01 17:25:58 -04:00
### Update
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
Once an Active Record object has been retrieved, its attributes can be modified
2012-12-12 12:40:51 -05:00
and it can be saved to the database.
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2013-06-30 19:38:46 -04:00
user = User.find_by(name: 'David')
2012-12-04 16:50:27 -05:00
user.name = 'Dave'
user.save
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
A shorthand for this is to use a hash mapping attribute names to the desired
2012-12-12 12:40:51 -05:00
value, like so:
```ruby
2013-06-30 19:38:46 -04:00
user = User.find_by(name: 'David')
2013-01-02 16:40:48 -05:00
user.update(name: 'Dave')
2012-12-12 12:40:51 -05:00
```
2013-04-03 07:18:20 -04:00
This is most useful when updating several attributes at once. If, on the other
hand, you'd like to update several records in bulk, you may find the
2012-12-12 12:40:51 -05:00
`update_all` class method useful:
```ruby
User.update_all "max_login_attempts = 3, must_change_password = 'true'"
```
2012-09-01 17:25:58 -04:00
### Delete
2009-08-13 12:02:01 -04:00
2013-04-03 07:18:20 -04:00
Likewise, once retrieved an Active Record object can be destroyed which removes
2012-12-12 12:40:51 -05:00
it from the database.
2009-08-13 12:02:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2013-06-30 19:38:46 -04:00
user = User.find_by(name: 'David')
2012-12-04 16:50:27 -05:00
user.destroy
2012-09-01 17:08:06 -04:00
```
2009-08-13 12:02:01 -04:00
2012-09-01 17:25:58 -04:00
Validations
-----------
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
Active Record allows you to validate the state of a model before it gets written
into the database. There are several methods that you can use to check your
models and validate that an attribute value is not empty, is unique and not
2012-12-12 12:40:51 -05:00
already in the database, follows a specific format and many more.
2014-05-06 19:46:55 -04:00
Validation is a very important issue to consider when persisting to the database, so
2014-07-21 04:48:37 -04:00
the methods `save` and `update` take it into account when
2013-04-03 07:18:20 -04:00
running: they return `false` when validation fails and they didn't actually
2014-05-06 19:46:55 -04:00
perform any operation on the database. All of these have a bang counterpart (that
2014-07-21 04:48:37 -04:00
is, `save!` and `update!` ), which are stricter in that
2013-04-03 07:18:20 -04:00
they raise the exception `ActiveRecord::RecordInvalid` if validation fails.
2012-12-12 12:40:51 -05:00
A quick example to illustrate:
```ruby
class User < ActiveRecord::Base
2013-04-05 11:15:53 -04:00
validates :name, presence: true
2012-12-12 12:40:51 -05:00
end
2014-07-21 04:48:37 -04:00
user = User.new
user.save # => false
user.save! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
2012-12-12 12:40:51 -05:00
```
2013-04-03 07:18:20 -04:00
You can learn more about validations in the [Active Record Validations
2012-12-12 12:40:51 -05:00
guide](active_record_validations.html).
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Callbacks
---------
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
Active Record callbacks allow you to attach code to certain events in the
life-cycle of your models. This enables you to add behavior to your models by
transparently executing code when those events occur, like when you create a new
record, update it, destroy it and so on. You can learn more about callbacks in
2012-12-12 12:40:51 -05:00
the [Active Record Callbacks guide ](active_record_callbacks.html ).
2009-08-13 12:02:01 -04:00
2012-09-01 17:25:58 -04:00
Migrations
----------
2009-02-05 20:57:02 -05:00
2013-04-03 07:18:20 -04:00
Rails provides a domain-specific language for managing a database schema called
migrations. Migrations are stored in files which are executed against any
2013-07-08 06:37:45 -04:00
database that Active Record supports using `rake` . Here's a migration that
2012-12-12 12:40:51 -05:00
creates a table:
```ruby
class CreatePublications < ActiveRecord::Migration
def change
create_table :publications do |t|
t.string :title
t.text :description
t.references :publication_type
t.integer :publisher_id
t.string :publisher_type
t.boolean :single_issue
2014-12-14 20:42:38 -05:00
t.timestamps null: false
2012-12-12 12:40:51 -05:00
end
add_index :publications, :publication_type_id
end
end
```
2013-04-03 07:18:20 -04:00
Rails keeps track of which files have been committed to the database and
2012-12-12 12:40:51 -05:00
provides rollback features. To actually create the table, you'd run `rake db:migrate`
and to roll it back, `rake db:rollback` .
2013-09-26 03:26:03 -04:00
Note that the above code is database-agnostic: it will run in MySQL,
PostgreSQL, Oracle and others. You can learn more about migrations in the
[Active Record Migrations guide ](migrations.html ).