aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/active_record_basics.txt
diff options
context:
space:
mode:
Diffstat (limited to 'railties/doc/guides/source/active_record_basics.txt')
-rw-r--r--railties/doc/guides/source/active_record_basics.txt225
1 files changed, 106 insertions, 119 deletions
diff --git a/railties/doc/guides/source/active_record_basics.txt b/railties/doc/guides/source/active_record_basics.txt
index 367a1bba5e..2336e162dc 100644
--- a/railties/doc/guides/source/active_record_basics.txt
+++ b/railties/doc/guides/source/active_record_basics.txt
@@ -1,154 +1,141 @@
Active Record Basics
====================
-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.
+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 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.
+After reading this guide we hope that you'll be able to:
-== ORM The Blueprint of Active Record
+* 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.
-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.
+== What's Active Record
-== Active Record The Engine of Rails
+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:
-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.
+* 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 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.
+The definition of the Active Record pattern in Martin Fowler's words:
-By following a few simple conventions the Rails Active Record will automatically map between:
+"_An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data."_
-* Classes & Database Tables
-* Class attributes & Database Table Columns
+== Object Relational Mapping
-=== Rails Active Record Conventions
-Here are the key conventions to consider when using Active Record.
+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.
-==== Naming Conventions
-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)
-Here are some additional Examples:
+== ActiveRecord as an ORM framework
-[grid="all"]
-`-------------`---------------
-Model / Class Table / Schema
-----------------------------
-Post posts
-LineItem line_items
-Deer deer
-Mouse mice
-Person people
-----------------------------
+ActiveRecord gives us several mechanisms, being the most important ones the hability to:
-==== Schema Conventions
+* 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.
-To take advantage of some of the magic of Rails database tables must be modeled
-to reflect the ORM decisions that Rails makes.
+It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern.
-[grid="all"]
-`-------------`---------------------------------------------------------------------------------
-Convention
--------------------------------------------------------------------------------------------------
-Foreign keys These fields are named table_id i.e. (item_id, order_id)
-Primary Key Rails automatically creates a primary key column named "id" unless told otherwise.
--------------------------------------------------------------------------------------------------
+== Active Record inside the MVC model
-==== Magic Field Names
+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.
-When these optional fields are used in your database table definition they give the Active Record
-instance additional features.
+== Convention over Configuration in ActiveRecord
-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.
+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.
-[grid="all"]
-`------------------------`------------------------------------------------------------------------------
-Attribute Purpose
-------------------------------------------------------------------------------------------------------
-created_at / created_on Rails stores the current date & time to this field when creating the record.
-updated_at / updated_on Rails stores the current date & time to this field when updating the record.
-lock_version Adds optimistic locking to a model link:http://api.rubyonrails.com/classes/ActiveRecord/Locking.html[more about optimistic locking].
-type Specifies that the model uses Single Table Inheritance link:http://api.rubyonrails.com/classes/ActiveRecord/Base.html[more about STI].
-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.
-_table_name_\_count Can be used to caches the number of belonging objects on the associated class.
-------------------------------------------------------------------------------------------------------
+=== Naming Conventions
-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.
+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:
-For example suppose you created a database table called cars:
+* 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.
+
+== 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]
--------------------------------------------------------
-mysql> CREATE TABLE cars (
- id INT,
- color VARCHAR(100),
- doors INT,
- horses INT,
- model VARCHAR(100)
- );
--------------------------------------------------------
-
-Now you created a class named Car, which is to represent an instance of a record from your table.
+------------------------------------------------------------------
+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]
--------------------------------------------------------
-class Car
-end
--------------------------------------------------------
+------------------------------------------------------------------
+p = Product.new
+p.name = "Some Book"
+puts p.name # "Some Book"
+------------------------------------------------------------------
+
+== Overriding the naming conventions
-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.
+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 the default conventions.
+You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
[source, ruby]
--------------------------------------------------------
->> c = Car.new
-=> #<Class:0x11e1e90>
->> c.doors
-NoMethodError: undefined method `doors' for #<Class:0x11e1e90>
- from (irb):2
--------------------------------------------------------
-
-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:
-“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.”
-Lets try our Car class again, this time inheriting from ActiveRecord.
+------------------------------------------------------------------
+class Product < ActiveRecord::Base
+ set_table_name "PRODUCT"
+end
+------------------------------------------------------------------
+It's also possible to override the column that should be used as the table's primary key. Use the +ActiveRecord::Base.set_primary_key+ method for that:
[source, ruby]
--------------------------------------------------------
-class Car < ActiveRecord::Base
+------------------------------------------------------------------
+class Product < ActiveRecord::Base
+ set_primary_key "product_id"
end
--------------------------------------------------------
+------------------------------------------------------------------
-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.
+== Validations
+
+ActiveRecord gives the hability to validate the state of your models before they get recorded into the database. There are several methods that you can use to hook into the lifecycle of your models and validate that an attribute value is not empty or follow a specific format and so on. You can learn more about validations in the http://guides.rails.info/activerecord_validations_callbacks.html#_overview_of_activerecord_validation[Active Record Validations and Callbacks guide].
+
+== Callbacks
+
+ActiveRecord callbacks allow you to attach code to certain events in the lifecycle of your models. This way you can add behaviour 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 the http://guides.rails.info/activerecord_validations_callbacks.html#_callbacks[Active Record Validations and Callbacks guide].
-[source, ruby]
--------------------------------------------------------
->> c = Car.new
-=> #<Car id: nil, doors: nil, color: nil, horses: nil, model: nil>
->> c.doors
-=> nil
--------------------------------------------------------
-
-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.
-- Associations between objects controlled by meta-programming macros.
-
-== 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. \ No newline at end of file