Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / source / active_record_basics.txt
1 Active Record Basics
2 ====================
3
4 Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of ActiveRecord.
5
6 After reading this guide readers should have 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 them a stronger and better developer.
7
8 == ORM The Blueprint of Active Record
9
10 If Active Record is the engine of Rails then ORM is the blueprint of that engine. ORM is short for “Object Relational Mapping” and is a programming concept used to make structures within a system relational. As a thought experiment imagine the components that make up a typical car. There are doors, seats, windows, engines etc. Viewed independently they are simple parts, yet when bolted together through the aid of a blueprint, the parts become a more complex device. ORM is the blueprint that describes how the individual parts relate to one another and in some cases infers the part’s purpose through the way the associations are described.
11
12 == Active Record The Engine of Rails
13
14 Active Record is a design pattern used to access data within a database. The name “Active Record” was coined by Martin Fowler in his book “Patterns of Enterprise Application Architecture”. Essentially, when a record is returned from the database instead of being just the data it is wrapped in a class, which gives you methods to control that data with. The rails framework is built around the MVC (Model View Controller) design patten and the Active Record is used as the default Model.
15
16 The Rails community added several useful concepts to their version of Active Record, including inheritance and associations, which are extremely useful for web applications. The associations are created by using a DSL (domain specific language) of macros, and inheritance is achieved through the use of STI (Single Table Inheritance) at the database level.
17
18 By following a few simple conventions the Rails Active Record will automatically map between:
19
20 * Classes & Database Tables
21 * Class attributes & Database Table Columns
22
23 === Rails Active Record Conventions
24 Here are the key conventions to consider when using Active Record.
25
26 ==== Naming Conventions
27 Database Table - Plural with underscores separating words i.e. (book_clubs)
28 Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
29 Here are some additional Examples:
30
31 [grid="all"]
32 `-------------`---------------
33 Model / Class Table / Schema
34 ----------------------------
35 Post posts
36 LineItem line_items
37 Deer deer
38 Mouse mice
39 Person people
40 ----------------------------
41
42 ==== Schema Conventions
43
44 To take advantage of some of the magic of Rails database tables must be modeled
45 to reflect the ORM decisions that Rails makes.
46
47 [grid="all"]
48 `-------------`---------------------------------------------------------------------------------
49 Convention
50 -------------------------------------------------------------------------------------------------
51 Foreign keys These fields are named table_id i.e. (item_id, order_id)
52 Primary Key Rails automatically creates a primary key column named "id" unless told otherwise.
53 -------------------------------------------------------------------------------------------------
54
55 ==== Magic Field Names
56
57 When these optional fields are used in your database table definition they give the Active Record
58 instance additional features.
59
60 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
61 used to designate a table using Single Table Inheritance. If you are not using STI, try an analogous
62 keyword like "context", that may still accurately describe the data you are modeling.
63
64 [grid="all"]
65 `------------------------`------------------------------------------------------------------------------
66 Attribute Purpose
67 ------------------------------------------------------------------------------------------------------
68 created_at / created_on Rails stores the current date & time to this field when creating the record.
69 updated_at / updated_on Rails stores the current date & time to this field when updating the record.
70 lock_version Adds optimistic locking to a model link:http://api.rubyonrails.com/classes/ActiveRecord/Locking.html[more about optimistic locking].
71 type Specifies that the model uses Single Table Inheritance link:http://api.rubyonrails.com/classes/ActiveRecord/Base.html[more about STI].
72 id All models require an id. the default is name is "id" but can be changed using the "set_primary_key" or "primary_key" methods.
73 _table_name_\_count Can be used to caches the number of belonging objects on the associated class.
74 ------------------------------------------------------------------------------------------------------
75
76 By default rails assumes all tables will use “id” as their primary key to identify each record. Though fortunately you won’t have explicitly declare this, Rails will automatically create that field unless you tell it not to.
77
78 For example suppose you created a database table called cars:
79
80 [source, sql]
81 -------------------------------------------------------
82 mysql> CREATE TABLE cars (
83 id INT,
84 color VARCHAR(100),
85 doors INT,
86 horses INT,
87 model VARCHAR(100)
88 );
89 -------------------------------------------------------
90
91 Now you created a class named Car, which is to represent an instance of a record from your table.
92
93 [source, ruby]
94 -------------------------------------------------------
95 class Car
96 end
97 -------------------------------------------------------
98
99 As you might expect without defining the explicit mappings between your class and the table it is impossible for Rails or any other program to correctly map those relationships.
100
101 [source, ruby]
102 -------------------------------------------------------
103 >> c = Car.new
104 => #<Class:0x11e1e90>
105 >> c.doors
106 NoMethodError: undefined method `doors' for #<Class:0x11e1e90>
107 from (irb):2
108 -------------------------------------------------------
109
110 Now you could define a door methods to write and read data to and from the database. In a nutshell this is what ActiveRecord does. According to the Rails API:
111 “Active Record objects don‘t specify their attributes directly, but rather infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.”
112 Lets try our Car class again, this time inheriting from ActiveRecord.
113
114 [source, ruby]
115 -------------------------------------------------------
116 class Car < ActiveRecord::Base
117 end
118 -------------------------------------------------------
119
120 Now if we try to access an attribute of the table ActiveRecord automatically handles the mappings for us, as you can see in the following example.
121
122 [source, ruby]
123 -------------------------------------------------------
124 >> c = Car.new
125 => #<Car id: nil, doors: nil, color: nil, horses: nil, model: nil>
126 >> c.doors
127 => nil
128 -------------------------------------------------------
129
130 Rails further extends this model by giving each ActiveRecord a way of describing the variety of ways records are associated with one another. We will touch on some of these associations later in the guide but I encourage readers who are interested to read the guide to ActiveRecord associations for an in-depth explanation of the variety of ways rails can model associations.
131 - Associations between objects controlled by meta-programming macros.
132
133 == Philosophical Approaches & Common Conventions
134 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
135
136 == ActiveRecord Magic
137 - timestamps
138 - updates
139
140 == How ActiveRecord Maps your Database.
141 - sensible defaults
142 - overriding conventions
143
144 == Growing Your Database Relationships Naturally
145
146 == Attributes
147 - attribute accessor method. How to override them?
148 - attribute?
149 - dirty records
150 -
151 == ActiveRecord handling the CRUD of your Rails application - Understanding the life-cycle of an ActiveRecord
152
153 == Validations & Callbacks
154 - Validations
155 * create!
156 * validates_acceptance_of
157 * validates_associated
158 * validates_confirmation_of
159 * validates_each
160 * validates_exclusion_of
161 * validates_format_of
162 * validates_inclusion_of
163 * validates_length_of
164 * validates_numericality_of
165 * validates_presence_of
166 * validates_size_of
167 * validates_uniqueness_of
168 - Callback
169 * (-) save
170 * (-) valid
171 * (1) before_validation
172 * (2) before_validation_on_create
173 * (-) validate
174 * (-) validate_on_create
175 * (3) after_validation
176 * (4) after_validation_on_create
177 * (5) before_save
178 * (6) before_create
179 * (-) create
180 * (7) after_create
181 * (8) after_save