aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/activerecord
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2008-10-21 15:58:29 +0100
committerPratik Naik <pratiknaik@gmail.com>2008-10-21 16:04:38 +0100
commit5265a8cd40a59ae792da3ed3f2a9648f15ecbd4e (patch)
tree44f66c3d1552e1821454658c653f062baada8668 /railties/doc/guides/activerecord
parentfa09de351c8045c7e7a0f268188ccf80c827b079 (diff)
downloadrails-5265a8cd40a59ae792da3ed3f2a9648f15ecbd4e.tar.gz
rails-5265a8cd40a59ae792da3ed3f2a9648f15ecbd4e.tar.bz2
rails-5265a8cd40a59ae792da3ed3f2a9648f15ecbd4e.zip
Rearrange guides
Diffstat (limited to 'railties/doc/guides/activerecord')
-rw-r--r--railties/doc/guides/activerecord/active_record_basics.txt120
-rw-r--r--railties/doc/guides/activerecord/association_basics.txt1838
-rw-r--r--railties/doc/guides/activerecord/basics.markdown56
-rw-r--r--railties/doc/guides/activerecord/finders.txt421
-rw-r--r--railties/doc/guides/activerecord/images/belongs_to.pngbin34017 -> 0 bytes
-rw-r--r--railties/doc/guides/activerecord/images/habtm.pngbin63801 -> 0 bytes
-rw-r--r--railties/doc/guides/activerecord/images/has_many.pngbin38582 -> 0 bytes
-rw-r--r--railties/doc/guides/activerecord/images/has_many_through.pngbin100220 -> 0 bytes
-rw-r--r--railties/doc/guides/activerecord/images/has_one.pngbin39022 -> 0 bytes
-rw-r--r--railties/doc/guides/activerecord/images/has_one_through.pngbin92594 -> 0 bytes
-rw-r--r--railties/doc/guides/activerecord/images/polymorphic.pngbin85248 -> 0 bytes
11 files changed, 0 insertions, 2435 deletions
diff --git a/railties/doc/guides/activerecord/active_record_basics.txt b/railties/doc/guides/activerecord/active_record_basics.txt
deleted file mode 100644
index 60ee1ef7b7..0000000000
--- a/railties/doc/guides/activerecord/active_record_basics.txt
+++ /dev/null
@@ -1,120 +0,0 @@
-ActiveRecord Basics
-=================================
-This guide will explain in detail how the ActiveRecord design pattern is used inside Ruby on Rails to make communication with the database clear and easy to understand.
-The intent of this guide is to explain the ActiveRecord implementation used by Rails though easy to understand examples, metaphors and detailed explanations of the actual Rails source code.
-After reading this guide readers should have a strong grasp of the ActiveRecord concept 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.
-== ORM The Blueprint of ActiveRecord
-If ActiveRecord 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. ORM seeks to give semantic meaning to the associations between elements of the system for example tables within a database.
-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.
-== ActiveRecord The Engine of Rails
-ActiveRecord is a metaphor used to access data within a database. The name “Active Record” was coined by Martin Fowler in his book “Patterns of Enterprise Application Architecture”. ActiveRecord is a conceptual model of the database record and the relationships to other records.
-As a side note, from now when I refer to ActiveRecord I’ll be referring to the specific Rails implementation and not the design pattern in general. I make this distinction because, as Rails has evolved so too has the Rails specific implementation of their version of ActiveRecord.
-Specifically, the Rails ActiveRecord pattern adds inheritance and associations. The associations are created by using a DSL (domain specific language) of macros, and a STI (Single Table Inheritance) to facilitate the inheritance.
-Rails uses ActiveRecord to abstract much of the drudgery or C.R.U.D (explained later) of working with data in databases. Using ActiveRecord Rails automates the mapping between:
-* Classes & Database Tables
-* Class attributes & Database Table Columns
-For example suppose you created a database table called cars:
-[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.
-[source, ruby]
--------------------------------------------------------
-class Car
-end
--------------------------------------------------------
-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.
-[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.
-[source, ruby]
--------------------------------------------------------
-class Car < ActiveRecord::Base
-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.
-[source, ruby]
--------------------------------------------------------
->> c = Car.new
-=> #<Car id: nil, doors: nil, color: nil, horses: nil, model: nil>
->> c.doors
-=> nil
--------------------------------------------------------
-
-This wrapper implements attribute accessors, callbacks and validations, which can make the data more powerful.
-- Validations
- * create!
- * validates_acceptance_of
- * validates_associated
- * validates_confirmation_of
- * validates_each
- * validates_exclusion_of
- * validates_format_of
- * validates_inclusion_of
- * validates_length_of
- * validates_numericality_of
- * validates_presence_of
- * validates_size_of
- * validates_uniqueness_of
- - Callback
- * (-) save
- * (-) valid
- * (1) before_validation
- * (2) before_validation_on_create
- * (-) validate
- * (-) validate_on_create
- * (3) after_validation
- * (4) after_validation_on_create
- * (5) before_save
- * (6) before_create
- * (-) create
- * (7) after_create
- * (8) after_save
-
-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 is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors. --wikipedia
-
- - Naming Conventions
- - Class Names are Singular
- - Tables names are the plural name of the class name
- - Tables contain an identity column named id
- - ids
-== 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 \ No newline at end of file
diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt
deleted file mode 100644
index 695b834652..0000000000
--- a/railties/doc/guides/activerecord/association_basics.txt
+++ /dev/null
@@ -1,1838 +0,0 @@
-A Guide to Active Record Associations
-=====================================
-
-This guide covers the association features of Active Record. By referring to this guide, you will be able to:
-
-* Declare associations between Active Record models
-* Understand the various types of Active Record associations
-* Use the methods added to your models by creating associations
-
-== Why Associations?
-
-Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
-end
-
-class Order < ActiveRecord::Base
-end
--------------------------------------------------------
-
-Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
-
-[source, ruby]
--------------------------------------------------------
-@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
--------------------------------------------------------
-
-Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
-
-[source, ruby]
--------------------------------------------------------
-@orders = Order.find_by_customer_id(@customer.id)
-@orders.each do |order|
- order.destroy
-end
-@customer.destroy
--------------------------------------------------------
-
-With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
--------------------------------------------------------
-
-With this change, creating a new order for a particular customer is easier:
-
-[source, ruby]
--------------------------------------------------------
-@order = @customer.orders.create(:order_date => Time.now)
--------------------------------------------------------
-
-Deleting a customer and all of its orders is _much_ easier:
-
-[source, ruby]
--------------------------------------------------------
-@customer.destroy
--------------------------------------------------------
-
-To learn more about the different types of associations, read the next section of this Guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
-
-== The Types of Associations
-
-In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
-
-* +belongs_to+
-* +has_one+
-* +has_many+
-* +has_many :through+
-* +has_one :through+
-* +has_and_belongs_to_many+
-
-In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
-
-=== The +belongs_to+ Association
-
-A +belongs_to+ association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
--------------------------------------------------------
-
-image:images/belongs_to.png[belongs_to Association Diagram]
-
-=== The +has_one+ Association
-
-A +has_one+ association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account
-end
--------------------------------------------------------
-
-image:images/has_one.png[has_one Association Diagram]
-
-=== The +has_many+ Association
-
-A +has_many+ association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a +belongs_to+ association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
-
-image:images/has_many.png[has_many Association Diagram]
-
-=== The +has_many :through+ Association
-
-A +has_many :through+ association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Physician < ActiveRecord::Base
- has_many :appointments
- has_many :patients, :through => :appointments
-end
-
-class Appointment < ActiveRecord::Base
- belongs_to :physician
- belongs_to :patient
-end
-
-class Patient < ActiveRecord::Base
- has_many :appointments
- has_many :physicians, :through => :appointments
-end
--------------------------------------------------------
-
-image:images/has_many_through.png[has_many :through Association Diagram]
-
-The +has_many :through+ association is also useful for setting up "shortcuts" through nested :+has_many+ associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Document < ActiveRecord::Base
- has_many :sections
- has_many :paragraphs, :through => :sections
-end
-
-class Section < ActiveRecord::Base
- belongs_to :document
- has_many :paragraphs
-end
-
-class Paragraph < ActiveRecord::Base
- belongs_to :section
-end
--------------------------------------------------------
-
-=== The +has_one :through+ Association
-
-A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account
- has_one :account_history, :through => :account
-end
-
-class Account < ActiveRecord::Base
- belongs_to :supplier
- has_one :account_history
-end
-
-class AccountHistory < ActiveRecord::Base
- belongs_to :account
-end
--------------------------------------------------------
-
-image:images/has_one_through.png[has_one :through Association Diagram]
-
-=== The +has_and_belongs_to_many+ Association
-
-A +has_and_belongs_to_many+ association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
-
-[source, ruby]
--------------------------------------------------------
-class Assembly < ActiveRecord::Base
- has_and_belongs_to_many :parts
-end
-
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
--------------------------------------------------------
-
-image:images/habtm.png[has_and_belongs_to_many Association Diagram]
-
-=== Choosing Between +belongs_to+ and +has_one+
-
-If you want to set up a 1-1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
-
-The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account
-end
-
-class Account < ActiveRecord::Base
- belongs_to :supplier
-end
--------------------------------------------------------
-
-The corresponding migration might look like this:
-
-[source, ruby]
--------------------------------------------------------
-class CreateSuppliers < ActiveRecord::Migration
- def self.up
- create_table :suppliers do |t|
- t.string :name
- t.timestamps
- end
-
- create_table :accounts do |t|
- t.integer :supplier_id
- t.string :account_number
- t.timestamps
- end
- end
-
- def self.down
- drop_table :accounts
- drop_table :suppliers
- end
-end
--------------------------------------------------------
-
-NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
-
-=== Choosing Between +has_many :through+ and +has_and_belongs_to_many+
-
-Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use +has_and_belongs_to_many+, which allows you to make the association directly:
-
-[source, ruby]
--------------------------------------------------------
-class Assembly < ActiveRecord::Base
- has_and_belongs_to_many :parts
-end
-
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
--------------------------------------------------------
-
-The second way to declare a many-to-many relationship is to use +has_many :through+. This makes the association indirectly, through a join model:
-
-[source, ruby]
--------------------------------------------------------
-class Assembly < ActiveRecord::Base
- has_many :manifests
- has_many :parts, :through => :manifests
-end
-
-class Manifest < ActiveRecord::Base
- belongs_to :assembly
- belongs_to :part
-end
-
-class Part < ActiveRecord::Base
- has_many :manifests
- has_many :assemblies, :through => :manifests
-end
--------------------------------------------------------
-
-The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
-
-You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
-
-=== Polymorphic Associations
-
-A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
-
-[source, ruby]
--------------------------------------------------------
-class Picture < ActiveRecord::Base
- belongs_to :imageable, :polymorphic => true
-end
-
-class Employee < ActiveRecord::Base
- has_many :pictures, :as => :imageable
-end
-
-class Product < ActiveRecord::Base
- has_many :pictures, :as => :imageable
-end
--------------------------------------------------------
-
-You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+. Similarly, you can retrieve +@product.pictures+. If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
-
-[source, ruby]
--------------------------------------------------------
-class CreatePictures < ActiveRecord::Migration
- def self.up
- create_table :pictures do |t|
- t.string :name
- t.integer :imageable_id
- t.string :imageable_type
- t.timestamps
- end
- end
-
- def self.down
- drop_table :pictures
- end
-end
--------------------------------------------------------
-
-This migration can be simplified by using the +t.references+ form:
-
-[source, ruby]
--------------------------------------------------------
-class CreatePictures < ActiveRecord::Migration
- def self.up
- create_table :pictures do |t|
- t.string :name
- t.references :imageable, :polymorphic => true
- t.timestamps
- end
- end
-
- def self.down
- drop_table :pictures
- end
-end
--------------------------------------------------------
-
-image:images/polymorphic.png[Polymorphic Association Diagram]
-
-=== Self Joins
-
-In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:
-
-[source, ruby]
--------------------------------------------------------
-class Employee < ActiveRecord::Base
- has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
- belongs_to :manager, :class_name => "User"
-end
--------------------------------------------------------
-
-With this setup, you can retrieve +@employee.subordinates+ and +@employee.managers+.
-
-== Tips, Tricks, and Warnings
-
-Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
-
-* Controlling caching
-* Avoiding name collisions
-* Updating the schema
-* Controlling association scope
-
-=== Controlling Caching
-
-All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
-
-[source, ruby]
--------------------------------------------------------
-customer.orders # retrieves orders from the database
-customer.orders.size # uses the cached copy of orders
-customer.orders.empty? # uses the cached copy of orders
--------------------------------------------------------
-
-But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass +true+ to the association call:
-
-[source, ruby]
--------------------------------------------------------
-customer.orders # retrieves orders from the database
-customer.orders.size # uses the cached copy of orders
-customer.orders(true).empty? # discards the cached copy of orders and goes back to the database
--------------------------------------------------------
-
-=== Avoiding Name Collisions
-
-You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of +ActiveRecord::Base+. The association method would override the base method and break things. For instance, +attributes+ or +connection+ are bad names for associations.
-
-=== Updating the Schema
-
-Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
--------------------------------------------------------
-
-This declaration needs to be backed up by the proper foreign key declaration on the orders table:
-
-[source, ruby]
--------------------------------------------------------
-class CreateOrders < ActiveRecord::Migration
- def self.up
- create_table :orders do |t|
- t.order_date :datetime
- t.order_number :string
- t.customer_id :integer
- end
- end
-
- def self.down
- drop_table :orders
- end
-end
--------------------------------------------------------
-
-If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key.
-
-Second, if you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
-
-WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
-
-Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
-
-[source, ruby]
--------------------------------------------------------
-class Assembly < ActiveRecord::Base
- has_and_belongs_to_many :parts
-end
-
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
--------------------------------------------------------
-
-These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:
-
-[source, ruby]
--------------------------------------------------------
-class CreateAssemblyPartJoinTable < ActiveRecord::Migration
- def self.up
- create_table :assemblies_parts, :id => false do |t|
- t.integer :assembly_id
- t.integer :part_id
- end
- end
-
- def self.down
- drop_table :assemblies_parts
- end
-end
--------------------------------------------------------
-
-=== Controlling Association Scope
-
-By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
-
-[source, ruby]
--------------------------------------------------------
-module MyApplication
- module Business
- class Supplier < ActiveRecord::Base
- has_one :account
- end
-
- class Account < ActiveRecord::Base
- belongs_to :supplier
- end
- end
-end
--------------------------------------------------------
-
-This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But this will not work, because +Supplier+ and +Account+ are defined in different scopes:
-
-[source, ruby]
--------------------------------------------------------
-module MyApplication
- module Business
- class Supplier < ActiveRecord::Base
- has_one :account
- end
- end
-
- module Billing
- class Account < ActiveRecord::Base
- belongs_to :supplier
- end
- end
-end
--------------------------------------------------------
-
-To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
-
-[source, ruby]
--------------------------------------------------------
-module MyApplication
- module Business
- class Supplier < ActiveRecord::Base
- has_one :account, :class_name => "MyApplication::Billing::Account"
- end
- end
-
- module Billing
- class Account < ActiveRecord::Base
- belongs_to :supplier, :class_name => "MyApplication::Business::Supplier"
- end
- end
-end
--------------------------------------------------------
-
-== Detailed Association Reference
-
-The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
-
-=== The +belongs_to+ Association
-
-The +belongs_to+ association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use +has_one+ instead.
-
-==== Methods Added by +belongs_to+
-
-When you declare a +belongs_to+ assocation, the declaring class automatically gains five methods related to the association:
-
-* +_association_(force_reload = false)+
-* +_association_=(associate)+
-* +_association_.nil?+
-* +build___association__(attributes = {})+
-* +create___association__(attributes = {})+
-
-In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
--------------------------------------------------------
-
-Each instance of the order model will have these methods:
-
-[source, ruby]
--------------------------------------------------------
-customer
-customer=
-customer.nil?
-build_customer
-create_customer
--------------------------------------------------------
-
-===== +_association_(force_reload = false)+
-
-The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
-
-[source, ruby]
--------------------------------------------------------
-@customer = @order.customer
--------------------------------------------------------
-
-If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
-
-===== +_association_=(associate)+
-
-The +_association_=+ method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
-
-[source, ruby]
--------------------------------------------------------
-@order.customer = @customer
--------------------------------------------------------
-
-===== +_association_.nil?+
-
-The +_association_.nil?+ method returns +true+ if there is no associated object.
-
-[source, ruby]
--------------------------------------------------------
-if @order.customer.nil?
- @msg = "No customer found for this order"
-end
--------------------------------------------------------
-
-===== +build___association__(attributes = {})+
-
-The +build__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
-
-[source, ruby]
--------------------------------------------------------
-@customer = @order.build_customer({:customer_number => 123, :customer_name => "John Doe"})
--------------------------------------------------------
-
-===== +create___association__(attributes = {})+
-
-The +create__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
-
-[source, ruby]
--------------------------------------------------------
-@customer = @order.create_customer({:customer_number => 123, :customer_name => "John Doe"})
--------------------------------------------------------
-
-==== Options for +belongs_to+
-
-In many situations, you can use the default behavior of +belongs_to+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +belongs_to+ association. For example, an association with several options might look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true, :conditions => "active = 1"
-end
--------------------------------------------------------
-
-The +belongs_to+ association supports these options:
-
-// * +:accessible+
-* +:class_name+
-* +:conditions+
-* +:counter_cache+
-* +:dependent+
-* +:foreign_key+
-* +:include+
-* +:polymorphic+
-* +:readonly+
-* +:select+
-* +:validate+
-
-// ===== +:accessible+
-//
-// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
-//
-===== +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => "Patron"
-end
--------------------------------------------------------
-
-===== +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :conditions => "active = 1"
-end
--------------------------------------------------------
-
-===== +:counter_cache+
-
-The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-With these declarations, asking for the value of +@customer.orders.size+ requires making a call to the database to perform a +COUNT(*)+ query. To avoid this call, you can add a counter cache to the _belonging_ model:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
-
-Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => :count_of_orders
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
-
-WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
-end
--------------------------------------------------------
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-===== +:include+
-
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
-
-[source, ruby]
--------------------------------------------------------
-class LineItem < ActiveRecord::Base
- belongs_to :order
-end
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
-
-[source, ruby]
--------------------------------------------------------
-class LineItem < ActiveRecord::Base
- belongs_to :order, :include => :customer
-end
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
-
-===== +:polymorphic+
-
-Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
-
-===== +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-
-===== +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-===== +:validate+
-
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-
-==== When are Objects Saved?
-
-Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
-
-=== The has_one Association
-
-The +has_one+ association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use +belongs_to+ instead.
-
-==== Methods Added by +has_one+
-
-When you declare a +has_one+ association, the declaring class automatically gains five methods related to the association:
-
-* +_association_(force_reload = false)+
-* +_association_=(associate)+
-* +_association_.nil?+
-* +build___association__(attributes = {})+
-* +create___association__(attributes = {})+
-
-In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account
-end
--------------------------------------------------------
-
-Each instance of the +Supplier+ model will have these methods:
-
-[source, ruby]
--------------------------------------------------------
-account
-account=
-account.nil?
-build_account
-create_account
--------------------------------------------------------
-
-===== +_association_(force_reload = false)+
-
-The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
-
-[source, ruby]
--------------------------------------------------------
-@account = @supplier.account
--------------------------------------------------------
-
-If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
-
-===== +_association_=(associate)+
-
-The +_association_=+ method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
-
-[source, ruby]
--------------------------------------------------------
-@suppler.account = @account
--------------------------------------------------------
-
-===== +_association_.nil?+
-
-The +_association_.nil?+ method returns +true+ if there is no associated object.
-
-[source, ruby]
--------------------------------------------------------
-if @supplier.account.nil?
- @msg = "No account found for this supplier"
-end
--------------------------------------------------------
-
-===== +build___association__(attributes = {})+
-
-The +build__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
-
-[source, ruby]
--------------------------------------------------------
-@account = @supplier.build_account({:terms => "Net 30"})
--------------------------------------------------------
-
-===== +create___association__(attributes = {})+
-
-The +create__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
-
-[source, ruby]
--------------------------------------------------------
-@account = @supplier.create_account({:terms => "Net 30"})
--------------------------------------------------------
-
-==== Options for +has_one+
-
-In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account, :class_name => "Billing", :dependent => :nullify
-end
--------------------------------------------------------
-
-The +has_one+ association supports these options:
-
-// * +:accessible+
-* +:as+
-* +:class_name+
-* +:conditions+
-* +:dependent+
-* +:foreign_key+
-* +:include+
-* +:order+
-* +:primary_key+
-* +:readonly+
-* +:select+
-* +:source+
-* +:source_type+
-* +:through+
-* +:validate+
-
-// ===== +:accessible+
-//
-// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
-//
-===== +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
-
-===== +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account, :class_name => "Billing"
-end
--------------------------------------------------------
-
-===== +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account, :conditions => "confirmed = 1"
-end
--------------------------------------------------------
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account, :foreign_key => "supp_id"
-end
--------------------------------------------------------
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-===== +:include+
-
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account
-end
-class Account < ActiveRecord::Base
- belongs_to :supplier
- belongs_to :representative
-end
-class Representative < ActiveRecord::Base
- has_many :accounts
-end
--------------------------------------------------------
-
-If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
-
-[source, ruby]
--------------------------------------------------------
-class Supplier < ActiveRecord::Base
- has_one :account, :include => :representative
-end
-class Account < ActiveRecord::Base
- belongs_to :supplier
- belongs_to :representative
-end
-class Representative < ActiveRecord::Base
- has_many :accounts
-end
--------------------------------------------------------
-
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-
-===== +:primary_key+
-
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-===== +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-
-===== +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-===== +:source+
-
-The +:source+ option specifies the source association name for a +has_one :through+ association.
-
-===== +:source_type+
-
-The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
-
-===== +:through+
-
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
-
-===== +:validate+
-
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-
-==== When are Objects Saved?
-
-When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
-
-If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
-
-If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved.
-
-If you want to assign an object to a +has_one+ association without saving the object, use the +association.build+ method.
-
-=== The has_many Association
-
-The +has_many+ association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
-
-==== Methods Added
-
-When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
-
-* +_collection_(force_reload = false)+
-* +_collection_<<(object, ...)+
-* +_collection_.delete(object, ...)+
-* +_collection_=objects+
-* +_collection\_singular_\_ids+
-* +_collection\_singular_\_ids=ids+
-* +_collection_.clear+
-* +_collection_.empty?+
-* +_collection_.size+
-* +_collection_.find(...)+
-* +_collection_.exist?(...)+
-* +_collection_.build(attributes = {}, ...)+
-* +_collection_.create(attributes = {})+
-
-In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection\_singular_+ is replaced with the singularized version of that symbol.. For example, given the declaration:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders
-end
--------------------------------------------------------
-
-Each instance of the customer model will have these methods:
-
-[source, ruby]
--------------------------------------------------------
-orders(force_reload = false)
-orders<<(object, ...)
-orders.delete(object, ...)
-orders=objects
-order_ids
-order_ids=ids
-orders.clear
-orders.empty?
-orders.size
-orders.find(...)
-orders.exist?(...)
-orders.build(attributes = {}, ...)
-orders.create(attributes = {})
--------------------------------------------------------
-
-===== +_collection_(force_reload = false)+
-
-The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
-
-[source, ruby]
--------------------------------------------------------
-@orders = @customer.orders
--------------------------------------------------------
-
-===== +_collection_<<(object, ...)+
-
-The +_collection_<<+ method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
-
-[source, ruby]
--------------------------------------------------------
-@customer.orders << @order1
--------------------------------------------------------
-
-===== +_collection_.delete(object, ...)+
-
-The +_collection_.delete+ method removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
-[source, ruby]
--------------------------------------------------------
-@customer.orders.delete(@order1)
--------------------------------------------------------
-
-WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
-
-
-===== +_collection_=objects+
-
-The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-
-===== +_collection\_singular_\_ids+
-
-The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
-
-[source, ruby]
--------------------------------------------------------
-@order_ids = @customer.order_ids
--------------------------------------------------------
-
-===== +__collection\_singular_\_ids=ids+
-
-The +__collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-
-===== +_collection_.clear+
-
-The +_collection_.clear+ method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.
-
-===== +_collection_.empty?+
-
-The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
-
-[source, ruby]
--------------------------------------------------------
-<% if @customer.orders.empty? %>
- No Orders Found
-<% end %>
--------------------------------------------------------
-
-===== +_collection_.size+
-
-The +_collection_.size+ method returns the number of objects in the collection.
-
-[source, ruby]
--------------------------------------------------------
-@order_count = @customer.orders.size
--------------------------------------------------------
-
-===== +_collection_.find(...)+
-
-The +_collection_.find+ method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
-
-[source, ruby]
--------------------------------------------------------
-@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
--------------------------------------------------------
-
-===== +_collection_.exist?(...)+
-
-The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
-
-===== +_collection_.build(attributes = {}, ...)+
-
-The +_collection_.build+ method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
-
-[source, ruby]
--------------------------------------------------------
-@order = @customer.orders.build({:order_date => Time.now, :order_number => "A12345"})
--------------------------------------------------------
-
-===== +_collection_.create(attributes = {})+
-
-The +_collection_.create+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
-
-[source, ruby]
--------------------------------------------------------
-@order = @customer.orders.create({:order_date => Time.now, :order_number => "A12345"})
--------------------------------------------------------
-
-==== Options for has_many
-
-In many situations, you can use the default behavior for +has_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :dependent => :delete_all, :validate => :false
-end
--------------------------------------------------------
-
-The +has_many+ association supports these options:
-
-// * +:accessible+
-* +:as+
-* +:class_name+
-* +:conditions+
-* +:counter_sql+
-* +:dependent+
-* +:extend+
-* +:finder_sql+
-* +:foreign_key+
-* +:group+
-* +:include+
-* +:limit+
-* +:offset+
-* +:order+
-* +:primary_key+
-* +:readonly+
-* +:select+
-* +:source+
-* +:source_type+
-* +:through+
-* +:uniq+
-* +:validate+
-
-// ===== +:accessible+
-//
-// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
-//
-===== +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
-
-===== +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :class_name => "Transaction"
-end
--------------------------------------------------------
-
-===== +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1"
-end
--------------------------------------------------------
-
-You can also set conditions via a hash:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true }
-end
--------------------------------------------------------
-
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
-
-===== +:counter_sql+
-
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
-
-NOTE: This option is ignored when you use the +:through+ option on the association.
-
-===== +:extend+
-
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
-
-===== +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :foreign_key => "cust_id"
-end
--------------------------------------------------------
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-===== +:group+
-
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :line_items, :through => :orders, :group => "orders.id"
-end
--------------------------------------------------------
-
-===== +:include+
-
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-class LineItem < ActiveRecord::Base
- belongs_to :order
-end
--------------------------------------------------------
-
-If you frequently retrieve line items directly from customers (+@customer.orders.line_items+), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :include => :line_items
-end
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-class LineItem < ActiveRecord::Base
- belongs_to :order
-end
--------------------------------------------------------
-
-===== +:limit+
-
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100
-end
--------------------------------------------------------
-
-===== +:offset+
-
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
-
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :order => "date_confirmed DESC"
-end
--------------------------------------------------------
-
-===== +:primary_key+
-
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-===== +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-
-===== +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-
-WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
-
-===== +:source+
-
-The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
-
-===== +:source_type+
-
-The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
-
-===== +:through+
-
-The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
-
-===== +:uniq+
-
-Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
-
-===== +:validate+
-
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-
-==== When are Objects Saved?
-
-When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
-
-If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
-
-If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
-
-If you want to assign an object to a +has_many+ association without saving the object, use the +_collection_.build+ method.
-
-=== The +has_and_belongs_to_many+ Association
-
-The +has_and_belongs_to_many+ association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
-
-==== Methods Added
-
-When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
-
-* +_collection_(force_reload = false)+
-* +_collection_<<(object, ...)+
-* +_collection_.delete(object, ...)+
-* +_collection_=objects+
-* +_collection\_singular_\_ids+
-* +_collection\_singular_\_ids=ids+
-* +_collection_.clear+
-* +_collection_.empty?+
-* +_collection_.size+
-* +_collection_.find(...)+
-* +_collection_.exist?(...)+
-* +_collection_.build(attributes = {})+
-* +_collection_.create(attributes = {})+
-
-In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection_\_singular+ is replaced with the singularized version of that symbol.. For example, given the declaration:
-
-[source, ruby]
--------------------------------------------------------
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
--------------------------------------------------------
-
-Each instance of the part model will have these methods:
-
-[source, ruby]
--------------------------------------------------------
-assemblies(force_reload = false)
-assemblies<<(object, ...)
-assemblies.delete(object, ...)
-assemblies=objects
-assembly_ids
-assembly_ids=ids
-assemblies.clear
-assemblies.empty?
-assemblies.size
-assemblies.find(...)
-assemblies.exist?(...)
-assemblies.build(attributes = {}, ...)
-assemblies.create(attributes = {})
--------------------------------------------------------
-
-===== Additional Column Methods
-
-If the join table for a +has_and_belongs_to_many+ association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
-
-WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+.
-
-
-===== +_collection_(force_reload = false)+
-
-The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
-
-[source, ruby]
--------------------------------------------------------
-@assemblies = @part.assemblies
--------------------------------------------------------
-
-===== +_collection_<<(object, ...)+
-
-The +_collection_<<+ method adds one or more objects to the collection by creating records in the join table.
-
-[source, ruby]
--------------------------------------------------------
-@part.assemblies << @assembly1
--------------------------------------------------------
-
-NOTE: This method is aliased as +_collection_.concat+ and +_collection_.push+.
-
-===== +_collection_.delete(object, ...)+
-
-The +_collection_.delete+ method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
-
-[source, ruby]
--------------------------------------------------------
-@part.assemblies.delete(@assembly1)
--------------------------------------------------------
-
-===== +_collection_=objects+
-
-The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-
-===== +_collection\_singular_\_ids+
-
-# Returns an array of the associated objects' ids
-
-The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
-
-[source, ruby]
--------------------------------------------------------
-@assembly_ids = @part.assembly_ids
--------------------------------------------------------
-
-===== +_collection\_singular_\_ids=ids+
-
-The +_collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-
-===== +_collection_.clear+
-
-The +_collection_.clear+ method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.
-
-===== +_collection_.empty?+
-
-The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
-
-[source, ruby]
--------------------------------------------------------
-<% if @part.assemblies.empty? %>
- This part is not used in any assemblies
-<% end %>
--------------------------------------------------------
-
-===== +_collection_.size+
-
-The +_collection_.size+ method returns the number of objects in the collection.
-
-[source, ruby]
--------------------------------------------------------
-@assembly_count = @part.assemblies.size
--------------------------------------------------------
-
-===== +_collection_.find(...)+
-
-The +_collection_.find+ method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
-
-[source, ruby]
--------------------------------------------------------
-@new_assemblies = @part.assemblies.find(:all, :conditions => ["created_at > ?", 2.days.ago])
--------------------------------------------------------
-
-===== +_collection_.exist?(...)+
-
-The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
-
-===== +_collection_.build(attributes = {})+
-
-The +_collection_.build+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
-
-[source, ruby]
--------------------------------------------------------
-@assembly = @part.assemblies.build({:assembly_name => "Transmission housing"})
--------------------------------------------------------
-
-===== +_collection_.create(attributes = {})+
-
-The +_collection_.create+ method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
-
-[source, ruby]
--------------------------------------------------------
-@assembly = @part.assemblies.create({:assembly_name => "Transmission housing"})
--------------------------------------------------------
-
-==== Options for has_and_belongs_to_many
-
-In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this:
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true
-end
--------------------------------------------------------
-
-The +has_and_belongs_to_many+ association supports these options:
-
-// * +:accessible+
-* +:association_foreign_key+
-* +:class_name+
-* +:conditions+
-* +:counter_sql+
-* +:delete_sql+
-* +:extend+
-* +:finder_sql+
-* +:foreign_key+
-* +:group+
-* +:include+
-* +:insert_sql+
-* +:join_table+
-* +:limit+
-* +:offset+
-* +:order+
-* +:readonly+
-* +:select+
-* +:uniq+
-* +:validate+
-
-// ===== +:accessible+
-//
-// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
-//
-===== +:association_foreign_key+
-
-By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
-
-TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
-
-[source, ruby]
--------------------------------------------------------
-class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
-end
--------------------------------------------------------
-
-===== +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :class_name => "Gadget"
-end
--------------------------------------------------------
-
-===== +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
-end
--------------------------------------------------------
-
-You can also set conditions via a hash:
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
-end
--------------------------------------------------------
-
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
-
-===== +:counter_sql+
-
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
-
-===== +:delete_sql+
-
-Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
-
-===== +:extend+
-
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
-
-===== +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-[source, ruby]
--------------------------------------------------------
-class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
-end
--------------------------------------------------------
-
-===== +:group+
-
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :group => "factory"
-end
--------------------------------------------------------
-
-===== +:include+
-
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
-
-===== +:insert_sql+
-
-Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
-
-===== +:join_table+
-
-If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
-
-===== +:limit+
-
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "created_at DESC", :limit => 50
-end
--------------------------------------------------------
-
-===== +:offset+
-
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
-
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
-end
--------------------------------------------------------
-
-===== +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-
-===== +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-
-===== +:uniq+
-
-Specify the +:uniq => true+ option to remove duplicates from the collection.
-
-===== +:validate+
-
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-
-==== When are Objects Saved?
-
-When you assign an object to a +has_and_belongs_to_many+ association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
-
-If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
-
-If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
-
-If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the +_collection_.build+ method.
-
-=== Association Callbacks
-
-Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved.
-
-Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
-
-* +before_add+
-* +after_add+
-* +before_remove+
-* +after_remove+
-
-You define association callbacks by adding options to the association declaration. For example:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :before_add => :check_credit_limit
-
- def check_credit_limit(order)
- ...
- end
-end
--------------------------------------------------------
-
-Rails passes the object being added or removed to the callback.
-
-You can stack callbacks on a single event by passing them as an array:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :before_add => [:check_credit_limit, :calculate_shipping_charges]
-
- def check_credit_limit(order)
- ...
- end
-
- def calculate_shipping_charges(order)
- ...
- end
-end
--------------------------------------------------------
-
-If a +before_add+ callback throws an exception, the object does not get added to the collection. Similarly, if a +before_remove+ callback throws an exception, the object does not get removed from the collection.
-
-=== Association Extensions
-
-You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders do
- def find_by_order_prefix(order_number)
- find_by_region_id(order_number[0..2])
- end
- end
-end
--------------------------------------------------------
-
-If you have an extension that should be shared by many associations, you can use a named extension module. For example:
-
-[source, ruby]
--------------------------------------------------------
-module FindRecentExtension
- def find_recent
- find(:all, :conditions => ["created_at > ?", 5.days.ago])
- end
-end
-
-class Customer < ActiveRecord::Base
- has_many :orders, :extend => FindRecentExtension
-end
-
-class Supplier < ActiveRecord::Base
- has_many :deliveries, :extend => FindRecentExtension
-end
--------------------------------------------------------
-
-To include more than one extension module in a single association, specify an array of names:
-
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :extend => [FindRecentExtension, FindActiveExtension]
-end
--------------------------------------------------------
-
-Extensions can refer to the internals of the association proxy using these three accessors:
-
-* +proxy_owner+ returns the object that the association is a part of.
-* +proxy_reflection+ returns the reflection object that describes the association.
-* +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
-
-== Changelog ==
-
-http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
-
-* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
-* September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
-* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/railties/doc/guides/activerecord/basics.markdown b/railties/doc/guides/activerecord/basics.markdown
deleted file mode 100644
index 0d030fabf9..0000000000
--- a/railties/doc/guides/activerecord/basics.markdown
+++ /dev/null
@@ -1,56 +0,0 @@
-Active Record Basics
-====================
-
-
-
-The ActiveRecord Pattern
-------------------------
-
-Active Record (the library) conforms to the active record design pattern. The active record pattern is a design pattern often found in applications that use relational database. The name comes from by Martin Fowler's book *Patterns of Enterprise Application Architecture*, in which he describes an active record object as:
-
-> An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.
-
-So, an object that follows the active record pattern encapsulates both data and behavior; in other words, they are responsible for saving and loading to the database and also for any domain logic that acts on the data. The data structure of the Active Record should exactly match that of the database: one field in the class for each column in the table.
-
-The Active Record class typically has methods that do the following:
-
-* Construct an instances of an Active Record class from a SQL result
-* Construct a new class instance for insertion into the table
-* Get and set column values
-* Wrap business logic where appropriate
-* Update existing objects and update the related rows in the database
-
-Mapping Your Database
----------------------
-
-### Plural tables, singular classes ###
-
-### Schema lives in the database ###
-
-Creating Records
-----------------
-
-### Using save ###
-
-### Using create ###
-
-Retrieving Existing Rows
-------------------------
-
-### Using find ###
-
-### Using find_by_* ###
-
-Editing and Updating Rows
--------------------------
-
-### Editing an instance
-
-### Using update_all/update_attributes ###
-
-Deleting Data
--------------
-
-### Destroying a record ###
-
-### Deleting a record ### \ No newline at end of file
diff --git a/railties/doc/guides/activerecord/finders.txt b/railties/doc/guides/activerecord/finders.txt
deleted file mode 100644
index e81fa23e3a..0000000000
--- a/railties/doc/guides/activerecord/finders.txt
+++ /dev/null
@@ -1,421 +0,0 @@
-Rails Finders
-=============
-
-This guide is all about the `find` method defined in ActiveRecord::Base, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.
-
-== In the beginning...
-
-In the beginning there was SQL. SQL looked like this:
-
-[source,sql]
-SELECT * FROM clients
-SELECT * FROM clients WHERE id = '1'
-SELECT * FROM clients LIMIT 0,1
-SELECT * FROM clients ORDER BY id DESC LIMIT 0,1
-
-In Rails you don't usually have to type SQL (unlike other languages) because ActiveRecord is there to help you find your records.
-
-== Our Models
-
-For this guide we have the following models:
-
-[source,ruby]
-class Client < ActiveRecord::Base
- has_one :address
- has_one :mailing_address
- has_many :orders
- has_and_belongs_to_many :roles
-end
-
-[source,ruby]
-class Address < ActiveRecord::Base
- belongs_to :client
-end
-
-[source,ruby]
-class MailingAddress < Address
-end
-
-[source,ruby]
-class Order < ActiveRecord::Base
- belongs_to :client, :counter_cache => true
-end
-
-[source,ruby]
-class Role < ActiveRecord::Base
- has_and_belongs_to_many :clients
-end
-
-== Database Agnostic
-
-ActiveRecord will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.
-
-== IDs, First, Last and All
-
-ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier: find. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type Client.find(1) which would execute this query on your database:
-
-[source, sql]
-SELECT * FROM `clients` WHERE (`clients`.`id` = 1)
-NOTE: Please be aware that because this is a standard table created from a migration in Rails that the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
-
-If you wanted to find clients with id 1 or 2, you call `Client.find([1,2])` or `Client.find(1,2)` and then this will be executed as:
-
-[source, sql]
-SELECT * FROM `clients` WHERE (`clients`.`id` IN (1,2))
-[source,txt]
->> Client.find(1,2)
-=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2, created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">, #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-
-Note that if you pass in a list of numbers that the result will be returned as an array, not an object of Client.
-
-If you wanted to find the first client you would simply type `Client.find(:first)` and that would find the first client created in your clients table:
-
-[source,txt]
->> Client.find(:first)
-=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2, created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
-If you were running script/server you may see the following output:
-
-[source,sql]
-SELECT * FROM clients LIMIT 1
-
-Indicating the query that Rails has performed on your database.
-
-To find the last client you would simply type `Client.find(:last)` and that would find the last client created in your clients table:
-
-[source,txt]
->> Client.find(:last)
-=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
-
-[source,sql]
-SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
-
-To find all the clients you would simply type `Client.find(:all)` and that would find all the clients in your clients table:
-
-[source,txt]
->> Client.find(:all)
-=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2, created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">, #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-
-Alternatively to calling Client.find(:first)/`Client.find(:last)`/`Client.find(:all)`, you could use the class method of `Client.first`/`Client.last`/`Client.all` instead. `Client.first`, `Client.last` and `Client.all` just call their longer counterparts.
-
-Be aware that `Client.first`/`Client.find(:first)` and `Client.last`/`Client.find(:last)` will both return a single object, where as `Client.all`/`Client.find(:all)` will return an array of Client objects, just as passing in an array of ids to find will do also.
-
-== Conditions
-
-If you'd like to add conditions to your find, you could just specify them in there, just like `Client.find(:first, :conditions => "orders_count = '2'")`. Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like `Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`. ActiveRecord will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like `Client.find(:first, :conditions => ["orders_count = ? AND locked = ?", params[:orders], false])`. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
-
-The reason for doing code like:
-
-[source, ruby]
-`Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`
-
-instead of:
-
-`Client.find(:first, :conditions => "orders_count = #{params[:orders]}")`
-
-is because of parameter safety. Putting the variable directly into the conditions string will parse the variable *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
-
-If you're looking for a range inside of a table for example users created in a certain timeframe you can use the conditions option coupled with the IN sql statement for this. If we had two dates coming in from a controller we could do something like this to look for a range:
-
-[source, ruby]
-Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date)])
-
-This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
-
-[source, sql]
-SELECT * FROM `users` WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05','2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11','2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17','2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
-2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20','2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26','2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
-
-
-Things can get *really* messy if you pass in time objects as it will attempt to compare your field to *every second* in that range:
-
-[source, ruby]
-Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
-
-[source, sql]
-SELECT * FROM `users` WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
-
-This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
-
-[source, txt]
-Got a packet bigger than 'max_allowed_packet' bytes: <query>
-
-Where <query> is the actual query used to get that error.
-
-In this example it would be better to use greater-than and less-than operators in SQL, like so:
-
-[source, ruby]
-Client.find(:all, :condtions => ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
-
-You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
-
-[source, ruby]
-Client.find(:all, :condtions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
-
-Just like in Ruby.
-
-== Ordering
-
-If you're getting a set of records and want to force an order, you can use `Client.find(:all, :order => "created_at")` which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using `Client.find(:all, :order => "created_at desc")`
-
-== Selecting Certain Fields
-
-To select certain fields, you can use the select option like this: `Client.find(:first, :select => "viewable_by, locked")`. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute `SELECT viewable_by, locked FROM clients LIMIT 0,1` on your database.
-
-== Limit & Offset
-
-If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
-
-[source, ruby]
-Client.find(:all, :limit => 5)
-
-This code will return a maximum of 5 clients and because we've specified no offset it will return the first 5 clients in the table. The SQL it executes will look like this:
-
-[source,sql]
-SELECT * FROM clients LIMIT 5
-
-[source, ruby]
-Client.find(:all, :limit => 5, :offset => 5)
-
-This code will return a maximum of 5 clients and because we have specified an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:
-
-[source,sql]
-SELECT * FROM clients LIMIT 5, 5
-
-== Group
-
-TODO
-
-== Read Only
-
-Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` error. To set this option, specify it like this:
-
-[source, ruby]
-Client.find(:first, :readonly => true)
-
-If you assign this record to a variable `client` calling the following code will raise an ActiveRecord::ReadOnlyRecord:
-
-[source, ruby]
-client = Client.find(:first, :readonly => true)
-client.locked = false
-client.save
-
-== Lock
-
-If you're wanting to stop race conditions for a specific record, say for example you're incrementing a single field for a record you can use the lock option to ensure that the record is updated correctly. It's recommended this be used inside a transaction.
-
-[source, Ruby]
-Topic.transaction do
- t = Topic.find(params[:id], :lock => true)
- t.increment!(:views)
-end
-
-== Making It All Work Together
-
-You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.
-
-== Eager Loading
-
-Eager loading is loading associated records along with any number of records in as few queries as possible. Lets say for example if we wanted to load all the addresses associated with all the clients all in the same query we would use `Client.find(:all, :include => :address)`. If we wanted to include both the address and mailing address for the client we would use `Client.find(:all), :include => [:address, :mailing_address]). Inclue will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
-
-[source, sql]
-Client Load (0.000383) SELECT * FROM clients
-Address Load (0.119770) SELECT addresses.* FROM addresses WHERE (addresses.client_id IN (13,14))
-MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
-
-The numbers `13` and `14` in the above SQL are the ids of the clients gathered from the `Client.find(:all)` query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called `address` or `mailing_address` on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
-
-An alternative (and more efficient) way to do eager loading is to use the joins option. For example if we wanted to get all the addresses for a client we would do `Client.find(:all, :joins => :address)` and if we wanted to find the address and mailing address for that client we would do `Client.find(:all, :joins => [:address, :mailing_address])`. This is more efficient because it does all the SQL in one query, as shown by this example:
-
-[source, sql]
-`Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses ON addresses.client_id = client.id INNER JOIN mailing_addresses ON mailing_addresses.client_id = client.id
-
-This query is more efficent, but there's a gotcha. If you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins.
-
-When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
-
-[source, Ruby]
-
-Client.find(:first, :include => "orders", :conditions => ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
-
-[source]
-
-== Dynamic finders
-
-With every field (also known as an attribute) you define in your table, ActiveRecord provides finder methods for these. If you have a field called `name` on your Client model for example, you get `find_by_name` and `find_all_by_name` for free from ActiveRecord. If you have also have a `locked` field on the client model, you also get `find_by_locked` and `find_all_by_locked`. If you want to find both by name and locked, you can chain these finders together by simply typing and between the fields for example `Client.find_by_name_and_locked('Ryan', true)`. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type `find_by_name(params[:name])` than it is to type `find(:first, :conditions => ["name = ?", params[:name]])`.
-
-There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like `find_or_create_by_name(params[:name])`. Using this will firstly perform a find and then create if the find returns nil, the SQL looks like this for `Client.find_or_create_by_name('Ryan')`:
-
-[source,sql]
-SELECT * FROM `clients` WHERE (`clients`.`name` = 'Ryan') LIMIT 1
-BEGIN
-INSERT INTO `clients` (`name`, `updated_at`, `created_at`, `orders_count`, `locked`) VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
-COMMIT
-
-`find_or_create`'s sibling, find_or_initialize, will find an object and if it does not exist will call `new` with the parameters you passed in. For example:
-
-[source, ruby]
-client = Client.find_or_initialize_by_name('Ryan')
-
-will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling `Client.new(:name => 'Ryan')`. From here, you can modify other fields in client by calling the attribute setters on it: `client.locked = true` and when you want to write it to the database just call `save` on it.
-
-== Finding By SQL
-
-If you'd like to use your own SQL to find records a table you can use `find_by_sql`. `find_by_sql` will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
-
-[source, ruby]
-Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
-
-`find_by_sql` provides you with a simple way of making custom calls to the database and converting those to objects.
-
-== Working with Associations
-
-When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like `Client.find(params[:id]).orders.find_by_sent_and_received(true, false)`. Having this find method available on associations is extremely helpful when using nested controllers.
-
-== Named Scopes
-
-In this section we'll cover adding named scopes to the models in the application. Let's say we want to find all clients who are male we would use this code:
-
-[source, ruby]
-class Client < ActiveRecord::Base
- named_scope :males, :conditions => { :gender => "male" }
-end
-
-And we could call it like `Client.males` to get all the clients who are male.
-
-If we wanted to find all the clients who are active, we could use this:
-
-[source,ruby]
-class Client < ActiveRecord::Base
- named_scope :active, :conditions => { :active => true }
-end
-
-We would call this new named_scope by doing `Client.active` and this will do the same query as if we just used `Client.find(:all, :conditions => ["active = ?", true])`. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do `Client.active.first`.
-
-and then if we wanted to find all the clients who are active and male we could stack the named scopes like this:
-
-[source, ruby]
-Client.males.active
-
-If you would then like to do a `find` on that subset of clients, you can. Just like an association, named scopes allow you to call `find` on a set of records:
-
-[source, ruby]
-Client.males.active.find(:all, :conditions => ["age > ?", params[:age]])
-
-Now observe the following code:
-
-[source, ruby]
-class Client < ActiveRecord::Base
- named_scope :recent, :conditions => { :created_at > 2.weeks.ago }
-end
-
-What we see here is what looks to be a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, `2.weeks.ago` is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
-
-[source, ruby]
-class Client < ActiveRecord::Base
- named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } }
-end
-
-And now every time the recent named scope is called, because it's wrapped in a lambda block this code will be parsed every time so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
-
-In a named scope you can use `:include` and `:joins` options just like in find.
-
-[source, ruby]
-class Client < ActiveRecord::Base
- named_scope :active_within_2_weeks, :joins => :order, lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
-end
-
-This method called as `Client.active_within_2_weeks` will return all clients who have placed orders in the past 2 weeks.
-
-If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
-
-[source, ruby]
-class Client < ActiveRecord::Base
- named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } } }
-end
-
-This will work if we call `Client.recent(2.weeks.ago)` but not if we call `Client.recent`. If we want to add an optional argument for this, we have to use the splat operator as the block's parameter.
-
-[source, ruby]
-class Client < ActiveRecord::Base
- named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } } }
-end
-
-This will work with `Client.recent(2.weeks.ago)` and `Client.recent` with the latter always returning records with a created_at date between right now and 2 weeks ago.
-
-Remember that named scopes are stackable, so you will be able to do `Client.recent(2.weeks.ago).unlocked` to find all clients created between right now and 2 weeks ago and have their locked field set to false.
-
-
-== Existance of Objects
-
-If you simply want to check for the existance of the object there's a method called `exists?`. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
-
-[source, ruby]
-Client.exists?(1)
-
-The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.
-
-[source, ruby]
-Client.exists?(1,2,3)
-# or
-Client.exists?([1,2,3])
-
-`exists?` also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
-
-Further more, `exists` takes a `conditions` option much like find:
-
-[source, ruby]
-Client.exists?(:conditions => "first_name = 'Ryan'")
-
-== Calculations
-
-=== Count
-
-If you want to see how many records are in your models table you could call `Client.count` and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use `Client.count(:age)`.
-
-`count` takes conditions much in the same way `exists?` does:
-
-[source, ruby]
-Client.count(:conditions => "first_name = 'Ryan'")
-
-[source, sql]
-SELECT count(*) AS count_all FROM `clients` WHERE (first_name = 1)
-
-== With Scope
-
-TODO
-
-== Credits
-
-Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.
-
-Thanks to Mike Gunderloy for his tips on creating this guide.
-
-== Change Log
-
-=== Sunday, 28 September 2008
-1. Changed "In Rails you don't have to type SQL" to "In Rails you don't usually have to type SQL"
-2. Inserted paragraph in dynamic finders about find_or_create and find_or_initialize
-3. Extended "First, Last, All" section.
-4. Renamed "First, Last & All" to "IDs, First, Last and All"
-5. Added finding by id and passing in ids to "IDs, First, Last and All"
-
-
-=== Wednesday, 01 October 2008
-1. Did section on limit and offset, as well as section on readonly.
-2. Altered formatting so it doesn't look bad.
-
-
-=== Sunday, 05 October 2008
-1. Extended conditions section to include IN and using operators inside the conditions.
-2. Extended conditions section to include paragraph and example of parameter safety.
-3. Added TODO sections.
-
-=== Monday, 06 October 2008
-1. Added section in Eager Loading about using conditions on tables that are not the model's own.
-
-=== Thursday, 09 October 2008
-1. Wrote section about lock option and tidied up "Making it all work together" section.
-2. Added section on using count.
-
-=== Tuesday, 21 October 2008
-1. Extended named scope guide by adding :include and :joins and find sub-sections.
diff --git a/railties/doc/guides/activerecord/images/belongs_to.png b/railties/doc/guides/activerecord/images/belongs_to.png
deleted file mode 100644
index 44243edbca..0000000000
--- a/railties/doc/guides/activerecord/images/belongs_to.png
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/habtm.png b/railties/doc/guides/activerecord/images/habtm.png
deleted file mode 100644
index fea78b0b5c..0000000000
--- a/railties/doc/guides/activerecord/images/habtm.png
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/has_many.png b/railties/doc/guides/activerecord/images/has_many.png
deleted file mode 100644
index 6cff58460d..0000000000
--- a/railties/doc/guides/activerecord/images/has_many.png
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/has_many_through.png b/railties/doc/guides/activerecord/images/has_many_through.png
deleted file mode 100644
index 85d7599925..0000000000
--- a/railties/doc/guides/activerecord/images/has_many_through.png
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/has_one.png b/railties/doc/guides/activerecord/images/has_one.png
deleted file mode 100644
index a70ddaaa86..0000000000
--- a/railties/doc/guides/activerecord/images/has_one.png
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/has_one_through.png b/railties/doc/guides/activerecord/images/has_one_through.png
deleted file mode 100644
index 89a7617a30..0000000000
--- a/railties/doc/guides/activerecord/images/has_one_through.png
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/polymorphic.png b/railties/doc/guides/activerecord/images/polymorphic.png
deleted file mode 100644
index ff2fd9f76d..0000000000
--- a/railties/doc/guides/activerecord/images/polymorphic.png
+++ /dev/null
Binary files differ