aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/active_record_basics.txt
blob: dd62b9a94879a7e69de49ba5bb9d4119dcef07ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
Active Record Basics
====================

This guide will give you a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make you a stronger and better developer.

After reading this guide we hope that you'll be able to:

* Understand the way Active Record fits into the MVC model.
* Create basic Active Record models and map them with your database tables.
* Use your models to execute CRUD (Create, Read, Update and Delete) database operations.
* Follow the naming conventions used by Rails to make developing database applications easier and obvious.
* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic. 
* Use Active Record with legacy databases that do not follow the Rails naming conventions.

== What's Active Record

Rails' ActiveRecord is an implementation of Martin Fowler's http://martinfowler.com/eaaCatalog/activeRecord.html[Active Record Design Pattern]. This pattern is based on the idea of creating relations between the database and the application in the following way:

* Each database table is mapped to a class.
* Each table column is mapped to an attribute of this class.
* Each instance of this class is mapped to a single row in the database table.

The definition of the Active Record pattern in Martin Fowler's words:

"_An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data."_

== Object Relational Mapping

The relation between databases and object-oriented software is called ORM, which is short for "Object Relational Mapping". The purpose of an ORM framework is to minimize the mismatch existent between relational databases and object-oriented software. In applications with a domain model, we have objects that represent both the state of the system and the behaviour of the real world elements that were modeled through these objects. Since we need to store the system's state somehow, we can use relational databases, which are proven to be an excelent approach to data management. Usually this may become a very hard thing to do, since we need to create an object-oriented model of everything that lives in the database, from simple columns to complicated relations between different tables. Doing this kind of thing by hand is a tedious and error prone job. This is where an ORM framework comes in.

== ActiveRecord as an ORM framework

ActiveRecord gives us several mechanisms, being the most important ones the hability to:

* Represent models.
* Represent associations between these models.
* Represent inheritance hierarquies through related models.
* Validate models before they get recorded to the database.
* Perform database operations in an object-oriented fashion.

It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern. 

== Active Record inside the MVC model

Active Record plays the role of model inside the MVC structure followed by Rails applications. Since model objects should encapsulate both state and logic of your applications, it's ActiveRecord responsability to deliver you the easiest possible way to recover this data from the database.

== Creating ActiveRecord models

It's very easy to create ActiveRecord models. All you have to do is to subclass the ActiveRecord::Base class and you're good to go:

[source, ruby]
------------------------------------------------------------------
class Product < ActiveRecord::Base; end
------------------------------------------------------------------

This will create a +Product+ model, mapped to a *products* table at the database. By doing this you'll also have the hability to map the columns of each row in that table with the attributes of the instances of your model. So, suppose that the *products* table was created using a SQL sentence like:

[source, sql]
------------------------------------------------------------------
CREATE TABLE products (
   id int(11) NOT NULL auto_increment,
   name varchar(255),
   PRIMARY KEY  (id)
);
------------------------------------------------------------------

Following the table schema above, you would be able to write code like the following:

[source, ruby]
------------------------------------------------------------------
p = Product.new
p.name = "Some Book"
puts p.name # "Some Book"
------------------------------------------------------------------

== Convention over Configuration in ActiveRecord

When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particulary true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating ActiveRecord models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicity configuration would be needed only in those cases where you can't follow the conventions for any reason.

=== Naming Conventions

By default, ActiveRecord 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 by underscores. Examples:

Database Table - Plural with underscores separating words i.e. (book_clubs)
Model Class - Singular with the first letter of each word capitalized i.e. (BookClub) 

[width="60%", options="header"]
|==============================
|Model / Class |Table / Schema 
|Post          |posts
|LineItem      |line_items
|Deer          |deer
|Mouse         |mice
|Person        |people
|==============================

=== Schema Conventions

ActiveRecord 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 table_id i.e. (item_id, order_id). These are the fields that ActiveRecord will look for when you create associations between your models.
* *Primary keys* - By default, ActiveRecord will use a integer column named "id" as the table's primary key. When using http://guides.rails.info/migrations.html[Rails Migrations] to create your tables, this column will be automaticaly created.

There are also some optional column names that will create additional features to ActiveRecord instances:

* *created_at / created_on* - ActiveRecord will store the current date and time to this field when creating the record.
* *updated_at / updated_on* - ActiveRecord will store the current date and times to this field when updating the record.
* *lock_version* - Adds http://api.rubyonrails.com/classes/ActiveRecord/Locking.html[optimistic locking] to a model.
* *type* - Specifies that the model uses http://api.rubyonrails.com/classes/ActiveRecord/Base.html[Single Table Inheritance]
* *(table_name)_count* - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.

NOTE: While these column names are optional they are in fact reserved by ActiveRecord. 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. If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.

 == STOPED HERE


== Philosophical Approaches & Common Conventions
Rails has a reputation of being a zero-config  framework which means that it aims to get you off the ground with as little pre-flight checking as possible. This speed benefit is achieved by following “Convention over Configuration”, which is to say that if you agree to live with the defaults then you benefit from a the inherent speed-boost. As Courtneay Gasking put it to me once “You don’t want to off-road on Rails”. ActiveRecord is no different, while it’s possible to override or subvert any of the conventions of AR, unless you have a good reason for doing so you will probably be happy with the defaults. The following is a list of the common conventions of ActiveRecord

== ActiveRecord Magic
 - timestamps
 - updates

== How ActiveRecord Maps your Database.
- sensible defaults
- overriding conventions

== Growing Your Database Relationships Naturally

== Attributes
 - attribute accessor method. How to override them?
 - attribute?
 - dirty records
 - 
== ActiveRecord handling the CRUD of your Rails application - Understanding the life-cycle of an ActiveRecord

== Validations & Callbacks
see the Validations & Callbacks guide for more info.