diff options
author | rick <technoweenie@gmail.com> | 2008-09-20 13:00:20 -0700 |
---|---|---|
committer | rick <technoweenie@gmail.com> | 2008-09-20 13:00:20 -0700 |
commit | 22e830f883af0b56de81186c184751b6398d0141 (patch) | |
tree | 0de20fad9f3a7ce2e49d660d1243b5b02a32e290 /railties/doc/guides | |
parent | 0aef9d1a2651fa0acd2adcd2de308eeb0ec8cdd2 (diff) | |
parent | a3b7fa78bfdc33e45e39c095b67e02d50a2c7bea (diff) | |
download | rails-22e830f883af0b56de81186c184751b6398d0141.tar.gz rails-22e830f883af0b56de81186c184751b6398d0141.tar.bz2 rails-22e830f883af0b56de81186c184751b6398d0141.zip |
Merge branch 'master' of git@github.com:rails/rails
Diffstat (limited to 'railties/doc/guides')
-rw-r--r-- | railties/doc/guides/activerecord/association_basics.txt | 1657 | ||||
-rw-r--r-- | railties/doc/guides/debugging/debugging_rails_applications.txt | 604 | ||||
-rw-r--r-- | railties/doc/guides/forms/form_helpers.txt | 270 | ||||
-rw-r--r-- | railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt | 348 | ||||
-rw-r--r-- | railties/doc/guides/index.txt | 53 | ||||
-rw-r--r-- | railties/doc/guides/migrations/anatomy_of_a_migration.txt | 85 | ||||
-rw-r--r-- | railties/doc/guides/migrations/creating_a_migration.txt | 109 | ||||
-rw-r--r-- | railties/doc/guides/migrations/foreign_keys.txt | 7 | ||||
-rw-r--r-- | railties/doc/guides/migrations/migrations.txt | 21 | ||||
-rw-r--r-- | railties/doc/guides/migrations/rakeing_around.txt | 111 | ||||
-rw-r--r-- | railties/doc/guides/migrations/scheming.txt | 47 | ||||
-rw-r--r-- | railties/doc/guides/migrations/using_models_in_migrations.txt | 46 | ||||
-rw-r--r-- | railties/doc/guides/migrations/writing_a_migration.txt | 159 | ||||
-rw-r--r-- | railties/doc/guides/routing/routing_outside_in.txt | 838 |
14 files changed, 4355 insertions, 0 deletions
diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt new file mode 100644 index 0000000000..9d950c91dd --- /dev/null +++ b/railties/doc/guides/activerecord/association_basics.txt @@ -0,0 +1,1657 @@ +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 customers model and an orders model. 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 enable 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 +------------------------------------------------------- + +=== 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 +------------------------------------------------------- + +=== 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 :customers +end +------------------------------------------------------- + +NOTE: The name of the other model is pluralized when declaring a +has_many+ association. + +=== 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 +------------------------------------------------------- + +=== 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 :account + has_one :account_history +end + +class AccountHistory < ActiveRecord::Base + belongs_to :account +end +------------------------------------------------------- + +=== 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 +------------------------------------------------------- + +=== 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 +------------------------------------------------------- + +=== 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 => :attachable +end + +class Product < ActiveRecord::Base + has_many :pictures, :as => :attachable +end +------------------------------------------------------- + +You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. 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 +------------------------------------------------------- + +== 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 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. + +You can associate a model with a model in a different scope, but only by specifying 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 +------------------------------------------------------- + +===== +: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 +------------------------------------------------------- + +===== +: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. + +===== +: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. + +===== +: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. + +===== +: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 => :customer_count +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+. + +WARNING: When you create a counter cache column in the database, be sure to specify a default value of zero. Otherwise, Rails will not properly maintain the counter. + +===== +: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 +------------------------------------------------------- + +===== +:polymorphic+ + +Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later 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. + +===== +: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. + +===== +: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. + +==== 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 order 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 this 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 +------------------------------------------------------- + +===== +: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 +------------------------------------------------------- + +===== +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +WHERE+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. + +===== +: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. + +===== +: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. + +===== +: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 +------------------------------------------------------- + +===== +:as+ + +Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide. + +===== +: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. + +===== +: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. + +===== +: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. + +===== +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. + +===== +: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. + +===== +: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. + +==== 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: The +_collection_.delete+ method will destroy the deleted object if they are declared as +belongs_to+ and are dependent on this model. + +===== +_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] +------------------------------------------------------- +@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 one 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 cover 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 +------------------------------------------------------- + +===== +: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 transactions, 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 => :orders, :conditions => "confirmed = 1" +end +------------------------------------------------------- + +You can also set conditions via a hash: + +[source, ruby] +------------------------------------------------------- +class Customer < ActiveRecord::Base + has_many :confirmed_orders, :class_name => :orders, :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+. + +===== +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +WHERE+ clause). + +[source, ruby] +------------------------------------------------------- +class Customer < ActiveRecord::Base + has_many :orders, :order => "date_confirmed DESC" +end +------------------------------------------------------- + +===== +: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. + +===== +: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. + +===== +: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+, 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. + +===== +: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. + +===== +: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. + +===== +:extend+ + +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide. + +===== +: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 :orders +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 :orders +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 Customer < ActiveRecord::Base + has_many :line_items, :through => :orders, :group => "orders.id" +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 => :orders, :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. + +===== +: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. + +===== +:as+ + +Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide. + +===== +: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. + +===== +: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. + +===== +:uniq+ + +Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option. + +===== +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. + +===== +: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. + +===== +: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. + +==== 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 Parts < 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 Field Methods + +If the join table for a +has_and_belongs_to_many+ association has additional fields beyond the two foreign keys, these fields 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. 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 +------------------------------------------------------- + +===== +: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 gadgets, you'd set things up this way: + +[source, ruby] +------------------------------------------------------- +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :class_name => :gadgets +end +------------------------------------------------------- + +===== +: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. + +===== +: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: + +===== +: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 => :users, + :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" +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". + +===== +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +WHERE+ clause). + + +[source, ruby] +------------------------------------------------------- +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :order => "assembly_name ASC" +end +------------------------------------------------------- + +===== +:uniq+ + +Specify the +:uniq => true+ option to remove duplicates from the collection. + +===== +: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. + +===== +: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. + +===== +: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. + +===== +:extend+ + +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide. + +===== +:include+ + +You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. + +===== +: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 +------------------------------------------------------- + +===== +: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. + +===== +: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. + +===== +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. + +===== +: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. + +===== +: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. + + +==== 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+. diff --git a/railties/doc/guides/debugging/debugging_rails_applications.txt b/railties/doc/guides/debugging/debugging_rails_applications.txt new file mode 100644 index 0000000000..eb1135d094 --- /dev/null +++ b/railties/doc/guides/debugging/debugging_rails_applications.txt @@ -0,0 +1,604 @@ +Debugging Rails applications +============================ + +This guide covers how to debug Ruby on Rails applications. By referring to this guide, you will be able to: + +* Understand the purpose of debugging +* Track down problems and issues in your application that your tests aren't identifying +* Learn the different ways of debugging +* Analyze the stack trace + +== View helpers for debugging + +=== debug + +`debug` will return a <pre>-tag that has object dumped by YAML. Generating readable output to inspect any object. + +[source, html] +---------------------------------------------------------------------------- +<%= debug @post %> +<p> + <b>Title:</b> + <%=h @post.title %> +</p> +---------------------------------------------------------------------------- + +Will render something like this: + +---------------------------------------------------------------------------- +--- !ruby/object:Post +attributes: + updated_at: 2008-09-05 22:55:47 + body: It's a very helpful guide for debugging your Rails app. + title: Rails debugging guide + published: t + id: "1" + created_at: 2008-09-05 22:55:47 +attributes_cache: {} + + +Title: Rails debugging guide +---------------------------------------------------------------------------- + + +=== do it yourself + +Displaying an instance variable, or any other object or method, in yaml format can be achieved this way: + +[source, html] +---------------------------------------------------------------------------- +<%= simple_format @post.to_yaml %> +<p> + <b>Title:</b> + <%=h @post.title %> +</p> +---------------------------------------------------------------------------- + +`to_yaml` converts the method to yaml format leaving it more readable and finally `simple_format` help us to render each line as in the console. This is how `debug` method does its magic. + +As a result of this, you will have something like this in your view: + +---------------------------------------------------------------------------- +--- !ruby/object:Post +attributes: +updated_at: 2008-09-05 22:55:47 +body: It's a very helpful guide for debugging your Rails app. +title: Rails debugging guide +published: t +id: "1" +created_at: 2008-09-05 22:55:47 +attributes_cache: {} + +Title: Rails debugging guide +---------------------------------------------------------------------------- + +Another useful method for displaying object values is `inspect`, especially when working with arrays or hashes, it will print the object value as a string, for example: + +[source, html] +---------------------------------------------------------------------------- +<%= [1, 2, 3, 4, 5].inspect %> +<p> + <b>Title:</b> + <%=h @post.title %> +</p> +---------------------------------------------------------------------------- + +Will be rendered as follows: + +---------------------------------------------------------------------------- +[1, 2, 3, 4, 5] + +Title: Rails debugging guide +---------------------------------------------------------------------------- + +== The logger + +=== What is it? + +Rails makes use of ruby’s standard `logger`, `Log4r`, or another logger that provides a similar interface can also be substituted if you wish. + +If you want to change the logger you can specify it in your `environment.rb` or any environment file. + +[source, ruby] +---------------------------------------------------------------------------- +ActiveRecord::Base.logger = Logger.new(STDOUT) +ActiveRecord::Base.logger = Log4r::Logger.new("Application Log") +---------------------------------------------------------------------------- + +Or in the `__Initializer__` section, add _any_ of the following + +[source, ruby] +---------------------------------------------------------------------------- +config.logger = Logger.new(STDOUT) +config.logger = Log4r::Logger.new("Application Log") +---------------------------------------------------------------------------- + +[TIP] +By default, each log is created under `RAILS_ROOT/log/` and the log file name is `environment_name.log`. + +=== Log levels + +When something is logged it's printed into the corresponding log if the message log level is equal or higher than the configured log level. If you want to know the current log level just call `ActiveRecord::Base.logger.level` method. + +The available log levels are: +:debug+, +:info+, +:warn+, +:error+, +:fatal+, each level has a log level number from 0 up to 4 respectively. To change the default log level, use + +[source, ruby] +---------------------------------------------------------------------------- +config.log_level = Logger::WARN # In any environment initializer, or +ActiveRecord::Base.logger.level = 0 # at any time +---------------------------------------------------------------------------- + +This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information. + +[TIP] +Rails default log level is +info+ in production mode and +debug+ in development and test mode. + +=== Sending messages + +To write in the current log use the `logger.(debug|info|warn|error|fatal)` method from within a controller, model or mailer: + +[source, ruby] +---------------------------------------------------------------------------- +logger.debug "Person attributes hash: #{@person.attributes.inspect}" +logger.info "Processing the request..." +logger.fatal "Terminating application, raised unrecoverable error!!!" +---------------------------------------------------------------------------- + +A common example: + +[source, ruby] +---------------------------------------------------------------------------- +class PostsController < ApplicationController + # ... + + def create + @post = Post.new(params[:post]) + logger.debug "New post: #{@post.attributes.inspect}" + logger.debug "Post should be valid: #{@post.valid?}" + + if @post.save + flash[:notice] = 'Post was successfully created.' + logger.debug "The post was saved and now is the user is going to be redirected..." + redirect_to(@post) + else + render :action => "new" + end + end + + # ... +end +---------------------------------------------------------------------------- + +Will be logged like this: + +---------------------------------------------------------------------------- +Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST] + Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4 + Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!", "published"=>"0"}, "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"} +New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!", "published"=>false, "created_at"=>nil} +Post should be valid: true + Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published", "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails', 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54') +The post was saved and now is the user is going to be redirected... +Redirected to #<Post:0x20af760> +Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts] +---------------------------------------------------------------------------- + +Notice the logged lines, now you can search for any unexpected behavior in the output. + +By now you should know how to use the logs in any environment. Remember to take advantage of the log levels and use them wisely, mostly in production mode. + +== Debugging with ruby-debug + +Many times your code may not behave as you expect, sometimes you will try to print in logs, console or view values to make a diagnostic of the problem. + +Unfortunately, you won't find always the answer you are looking for this way. In that case, you will need to know what's happening and adventure into Rails, in this journey the debugger will be your best companion. + +If you ever wanted to learn about Rails source code but you didn't know where to start, this may be the best way, just debug any request to your application and use this guide to learn how to move in the code you have written but also go deeper into Rails code. + +=== Setup + +Ruby-debug comes as a gem so to install, just run: + +---------------------------------------------------------------------------- +$ sudo gem in ruby-debug +---------------------------------------------------------------------------- + +In case you want to download a particular version or get the source code, refer to link:http://rubyforge.org/projects/ruby-debug/[project's page on rubyforge]. + +Rails has built-in support for ruby-debug since April 28, 2007. Inside any Rails application you can invoke the debugger by calling the `debugger` method. + +Let's take a look at an example: + +[source, ruby] +---------------------------------------------------------------------------- +class PeopleController < ApplicationController + def new + debugger + @person = Person.new + end +end +---------------------------------------------------------------------------- + +If you see the message in the console or logs: + +---------------------------------------------------------------------------- +***** Debugger requested, but was not available: Start server with --debugger to enable ***** +---------------------------------------------------------------------------- + +Make sure you have started your web server with the option --debugger: + +---------------------------------------------------------------------------- +~/PathTo/rails_project$ script/server --debugger +---------------------------------------------------------------------------- + +[TIP] +In development mode, you can dynamically `require \'ruby-debug\'` instead of restarting the server, in case it was started without `--debugger`. + +In order to use Rails debugging you'll need to be running either *WEBrick* or *Mongrel*. For the moment, no alternative servers are supported. + +=== The shell + +As soon as your application calls the `debugger` method, the debugger will be started in a debugger shell inside the terminal window you've fired up your application server and you will be placed in the ruby-debug's prompt `(rdb:n)`. The _n_ is the thread number. + +If you got there by a browser request, the browser will be hanging until the debugger has finished and the trace has completely run as any normal request. + +For example: + +---------------------------------------------------------------------------- +@posts = Post.find(:all) +(rdb:7) +---------------------------------------------------------------------------- + +Now it's time to play and dig into our application. The first we are going to do is ask our debugger for help... so we type: `help` (You didn't see that coming, right?) + +---------------------------------------------------------------------------- +(rdb:7) help +ruby-debug help v0.10.2 +Type 'help <command-name>' for help on a specific command + +Available commands: +backtrace delete enable help next quit show trace +break disable eval info p reload source undisplay +catch display exit irb pp restart step up +condition down finish list ps save thread var +continue edit frame method putl set tmate where +---------------------------------------------------------------------------- + +[TIP] +To view the help menu for any command use `help <command-name>` in active debug mode. For example: _help var_ + +The second command before we move on, is one of the most useful command: `list` (or his shorthand `l`). + +This command will give us a starting point of where we are by printing 10 lines centered around the current line; the current line here is line 6 and is marked by =>. + +---------------------------------------------------------------------------- +(rdb:7) list +[1, 10] in /PathToProject/posts_controller.rb + 1 class PostsController < ApplicationController + 2 # GET /posts + 3 # GET /posts.xml + 4 def index + 5 debugger +=> 6 @posts = Post.find(:all) + 7 + 8 respond_to do |format| + 9 format.html # index.html.erb + 10 format.xml { render :xml => @posts } +---------------------------------------------------------------------------- + +If we do it again, this time using just `l`, the next ten lines of the file will be printed out. + +---------------------------------------------------------------------------- +(rdb:7) l +[11, 20] in /PathTo/project/app/controllers/posts_controller.rb + 11 end + 12 end + 13 + 14 # GET /posts/1 + 15 # GET /posts/1.xml + 16 def show + 17 @post = Post.find(params[:id]) + 18 + 19 respond_to do |format| + 20 format.html # show.html.erb +---------------------------------------------------------------------------- + +And so on until the end of the current file, when the end of file is reached, it will start again from the beginning of the file and continue again up to the end, acting as a circular buffer. + +=== The context +When we start debugging your application, we will be placed in different contexts as you go through the different parts of the stack. + +A context will be created when a stopping point or an event is reached. It has information about the suspended program which enable a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place the debugged program is stopped. + +At any time we can call the `backtrace` command (or alias `where`) to print the backtrace of the application, this is very helpful to know how we got where we are. If you ever wondered about how you got somewhere in your code, then `backtrace` is your answer. + +---------------------------------------------------------------------------- +(rdb:5) where + #0 PostsController.index + at line /PathTo/project/app/controllers/posts_controller.rb:6 + #1 Kernel.send + at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 + #2 ActionController::Base.perform_action_without_filters + at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 + #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...) + at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617 +... +---------------------------------------------------------------------------- + +You move anywhere you want in this trace using the `frame _n_` command, where _n_ is the specified frame number. + +---------------------------------------------------------------------------- +(rdb:5) frame 2 +#2 ActionController::Base.perform_action_without_filters + at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 +---------------------------------------------------------------------------- + +The available variables are the same as if we were running the code line by line, after all, that's what debugging is. + +Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) and `down [n]` commands in order to change the context _n_ frames up or down the stack respectively. _n_ defaults to one. + +=== Threads + +The debugger can list, stop, resume and switch between running threads, the command `thread` (or the abbreviated `th`) is used an allows the following options: + +* `thread` shows the current thread. +* `thread list` command is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution. +* `thread stop _n_` stop thread _n_. +* `thread resume _n_` resume thread _n_. +* `thread switch _n_` switch thread context to _n_. + +This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code. + +=== Inspecting variables + +Any expression can be evaluated in the current context, just type it! + +In the following example we will print the instance_variables defined within the current context. + +---------------------------------------------------------------------------- +@posts = Post.find(:all) +(rdb:11) instance_variables +["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"] +---------------------------------------------------------------------------- + +As you may have figured out, all variables that you can access from a controller are displayed, lets run the next line, we will use `next` (we will get later into this command). + +---------------------------------------------------------------------------- +(rdb:11) next +Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET] + Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e + Parameters: {"action"=>"index", "controller"=>"posts"} +/PathToProject/posts_controller.rb:8 +respond_to do |format| +------------------------------------------------------------------------------- + +And we'll ask again for the instance_variables. + +---------------------------------------------------------------------------- +(rdb:11) instance_variables.include? "@posts" +true +---------------------------------------------------------------------------- + +Now +@posts+ is a included in them, because the line defining it was executed. + +[TIP] +You can also step into *irb* mode with the command `irb` (of course!). This way an irb session will be started within the context you invoked it. But you must know that this is an experimental feature. + +To show variables and their values the `var` method is the most convenient way: + +---------------------------------------------------------------------------- +var +(rdb:1) v[ar] const <object> show constants of object +(rdb:1) v[ar] g[lobal] show global variables +(rdb:1) v[ar] i[nstance] <object> show instance variables of object +(rdb:1) v[ar] l[ocal] show local variables +---------------------------------------------------------------------------- + +This is a great way for inspecting the values of the current context variables. For example: + +---------------------------------------------------------------------------- +(rdb:9) var local + __dbg_verbose_save => false +---------------------------------------------------------------------------- + +You can also inspect for an object method this way: + +---------------------------------------------------------------------------- +(rdb:9) var instance Post.new +@attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"... +@attributes_cache = {} +@new_record = true +---------------------------------------------------------------------------- + +[TIP] +Commands `p` (print) and `pp` (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console. + +We can use also `display` to start watching variables, this is a good way of tracking values of a variable while the execution goes on. + +---------------------------------------------------------------------------- +(rdb:1) display @recent_comments +1: @recent_comments = +---------------------------------------------------------------------------- + +The variables inside the displaying list will be printed with their values after we move in the stack. To stop displaying a variable use `undisplay _n_` where _n_ is the variable number (1 in the last example). + +=== Step by step + +Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution. + +Use `step` (abbreviated `s`) to continue running your program until the next logical stopping point and return control to ruby-debug. + +[TIP] +You can also use `step+ _n_` and `step- _n_` to move forward or backward _n_ steps respectively. + +You may also use `next` which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move _n_ steps. + +The difference between `next` and `step` is that `step` stops at the next line of code executed, doing just single step, while `next` moves to the next line without descending inside methods. + +Lets run the next line in this example: + +[source, ruby] +---------------------------------------------------------------------------- +class Author < ActiveRecord::Base + has_one :editorial + has_many :comments + + def find_recent_comments(limit = 10) + debugger + @recent_comments ||= comments.find( + :all, + :conditions => ["created_at > ?", 1.week.ago], + :limit => limit + ) + end +end +---------------------------------------------------------------------------- + +[TIP] +You can use ruby-debug while using script/console but remember to `require "ruby-debug"` before calling `debugger` method. + +---------------------------------------------------------------------------- +/PathTo/project $ script/console +Loading development environment (Rails 2.1.0) +>> require "ruby-debug" +=> [] +>> author = Author.first +=> #<Author id: 1, first_name: "Bob", last_name: "Smith", created_at: "2008-07-31 12:46:10", updated_at: "2008-07-31 12:46:10"> +>> author.find_recent_comments +/PathTo/project/app/models/author.rb:11 +) +---------------------------------------------------------------------------- + +Now we are where we wanted to be, lets look around. + +---------------------------------------------------------------------------- +(rdb:1) list +[6, 15] in /PathTo/project/app/models/author.rb + 6 debugger + 7 @recent_comments ||= comments.find( + 8 :all, + 9 :conditions => ["created_at > ?", 1.week.ago], + 10 :limit => limit +=> 11 ) + 12 end + 13 end +---------------------------------------------------------------------------- + +We are at the end of the line, but... was this line executed? We can inspect the instance variables. + +---------------------------------------------------------------------------- +(rdb:1) var instance +@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... +@attributes_cache = {} +---------------------------------------------------------------------------- + ++@recent_comments+ hasn't been defined yet, so we can assure this line hasn't been executed yet, lets move on this code. + +---------------------------------------------------------------------------- +(rdb:1) next +/PathTo/project/app/models/author.rb:12 +@recent_comments +(rdb:1) var instance +@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... +@attributes_cache = {} +@comments = [] +@recent_comments = [] +---------------------------------------------------------------------------- + +Now we can see how +@comments+ relationship was loaded and @recent_comments defined because the line was executed. + +In case we want deeper in the stack trace we can move single `steps` and go into Rails code, this is the best way for finding bugs in your code, or maybe in Ruby or Rails. + +=== Breakpoints + +A breakpoint makes your application stop whenever a certain point in the program is reached and the debugger shell is invoked in that line. + +You can add breakpoints dynamically with the command `break` (or just `b`), there are 3 possible ways of adding breakpoints manually: + +* `break line`: set breakpoint in the _line_ in the current source file. +* `break file:line [if expression]`: set breakpoint in the _line_ number inside the _file_. If an _expression_ is given it must evaluated to _true_ to fire up the debugger. +* `break class(.|\#)method [if expression]`: set breakpoint in _method_ (. and \# for class and instance method respectively) defined in _class_. The _expression_ works the same way as with file:line. + +---------------------------------------------------------------------------- +(rdb:5) break 10 +Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10 +---------------------------------------------------------------------------- + +Use `info breakpoints _n_` or `info break _n_` lo list breakpoints, is _n_ is defined it shows that breakpoints, otherwise all breakpoints are listed. + +---------------------------------------------------------------------------- +(rdb:5) info breakpoints +Num Enb What + 1 y at filters.rb:10 +---------------------------------------------------------------------------- + +Deleting breakpoints: use the command `delete _n_` to remove the breakpoint number _n_ or all of them if _n_ is not specified. + +---------------------------------------------------------------------------- +(rdb:5) delete 1 +(rdb:5) info breakpoints +No breakpoints. +---------------------------------------------------------------------------- + +Enabling/Disabling breakpoints: + +* `enable breakpoints`: allow a list _breakpoints_ or all of them if none specified, to stop your program (this is the default state when you create a breakpoint). +* `disable breakpoints`: the _breakpoints_ will have no effect on your program. + +=== Catching Exceptions + +The command `catch exception-name` (or just `cat exception-name`) can be used to intercept an exception of type _exception-name_ when there would otherwise be is no handler for it. + +To list existent catchpoints use `catch`. + +=== Resuming Execution + +* `continue` [line-specification] (or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached. +* `finish` [frame-number] (or `fin`): execute until selected stack frame returns. If no frame number is given, we run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given we run until frame frames returns. + +=== Editing + +At any time, you may use any of this commands to edit the code you are evaluating: + +* `edit [file:line]`: edit _file_ using the editor specified by the EDITOR environment variable. A specific _line_ can also be given. +* `tmate _n_` (abbreviated `tm`): open the current file in TextMate. It uses n-th frame if _n_ is specified. + +=== Quitting +To exit the debugger, use the `quit` command (abbreviated `q`), or alias `exit`. + +A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again. + +=== Settings + +There are some settings that can be configured in ruby-debug to make it easier to debug your code, being among others useful options: + +* `set reload`: Reload source code when changed. +* `set autolist`: Execute `list` command on every breakpoint. +* `set listsize _n_`: Set number of source lines to list by default _n_. +* `set forcestep`: Make sure `next` and `step` commands always move to a new line + +You can see the full list by using `help set` or `help set subcommand` to inspect any of them. + +[TIP] +You can include any number of this configuration lines inside a `.rdebugrc` file in your HOME directory, and ruby-debug will read it every time it is loaded + +The following lines are recommended to be included in `.rdebugrc`: + +---------------------------------------------------------------------------- +set autolist +set forcestep +set listsize 25 +---------------------------------------------------------------------------- + + +== References + +* link:http://www.datanoise.com/ruby-debug[ruby-debug Homepage] +* link:http://www.sitepoint.com/article/debug-rails-app-ruby-debug/[Article: Debugging a Rails application with ruby-debug] +* link:http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/[ruby-debug Basics screencast] +* link:http://railscasts.com/episodes/54-debugging-with-ruby-debug[Ryan Bate's ruby-debug screencast] +* link:http://railscasts.com/episodes/24-the-stack-trace[Ryan Bate's stack trace screencast] +* link:http://railscasts.com/episodes/56-the-logger[Ryan Bate's logger screencast] +* link:http://bashdb.sourceforge.net/ruby-debug.html[Debugging with ruby-debug] +* link:http://cheat.errtheblog.com/s/rdebug/[ruby-debug cheat sheet] +* link:http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging[Ruby on Rails Wiki: How to Configure Logging]
\ No newline at end of file diff --git a/railties/doc/guides/forms/form_helpers.txt b/railties/doc/guides/forms/form_helpers.txt new file mode 100644 index 0000000000..7b0aeb0ed9 --- /dev/null +++ b/railties/doc/guides/forms/form_helpers.txt @@ -0,0 +1,270 @@ +Rails form helpers +================== +Mislav Marohnić <mislav.marohnic@gmail.com> + +Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use. + +In this guide we will: + +* Create search forms and similar kind of generic forms not representing any specific model in your application; +* Make model-centric forms for creation and editing of specific database records; +* Generate select boxes from multiple types of data; +* Learn what makes a file upload form different; +* Build complex, multi-model forms. + +NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit http://api.rubyonrails.org/[the Rails API documentation] for a complete reference. + + +Basic forms +----------- + +The most basic form helper is `form_tag`. + +---------------------------------------------------------------------------- +<% form_tag do %> + Form contents +<% end %> +---------------------------------------------------------------------------- + +When called without arguments like this, it creates a form element that has the current page for action attribute and "POST" as method (some line breaks added for readability): + +.Sample rendering of `form_tag` +---------------------------------------------------------------------------- +<form action="/home/index" method="post"> + <div style="margin:0;padding:0"> + <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> + </div> + Form contents +</form> +---------------------------------------------------------------------------- + +If you carefully observe this output, you can see that the helper generated something we didn't specify: a `div` element with a hidden input inside. This is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form which action isn't "GET" (provided that this security feature is enabled). + +NOTE: Throughout this guide, this `div` with the hidden input will be stripped away to have clearer code samples. + +Generic search form +~~~~~~~~~~~~~~~~~~~ + +Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of: + +1. a form element with "GET" method, +2. a label for the input, +3. a text input element, and +4. a submit element. + +IMPORTANT: Always use "GET" as the method for search forms. Benefits are many: users are able to bookmark a specific search and get back to it; browsers cache results of "GET" requests, but not "POST"; and other. + +To create that, we will use `form_tag`, `label_tag`, `text_field_tag` and `submit_tag`, respectively. + +.A basic search form +---------------------------------------------------------------------------- +<% form_tag(search_path, :method => "get") do %> + <%= label_tag(:q, "Search for:") %> + <%= text_field_tag(:q) %> + <%= submit_tag("Search") %> +<% end %> +---------------------------------------------------------------------------- + +[TIP] +============================================================================ +`search_path` can be a named route specified in "routes.rb": + +---------------------------------------------------------------------------- +map.search "search", :controller => "search" +---------------------------------------------------------------------------- +============================================================================ + +The above view code will result in the following markup: + +.Search form HTML +---------------------------------------------------------------------------- +<form action="/search" method="get"> + <label for="q">Search for:</label> + <input id="q" name="q" type="text" /> + <input name="commit" type="submit" value="Search" /> +</form> +---------------------------------------------------------------------------- + +Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML. + +TIP: For every form input, an ID attribute is generated from its name ("q" in our example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript. + +Multiple hashes in form helper attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By now we've seen that the `form_tag` helper accepts 2 arguments: the path for the action attribute and an options hash for parameters (like `:method`). + +Identical to the `link_to` helper, the path argument doesn't have to be given as string or a named route. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. Still, we cannot simply write this: + +.A bad way to pass multiple hashes as method arguments +---------------------------------------------------------------------------- +form_tag(:controller => "people", :action => "search", :method => "get") +# => <form action="/people/search?method=get" method="post"> +---------------------------------------------------------------------------- + +Here we wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL that we didn't want. The solution is to delimit the first hash (or both hashes) with curly brackets: + +.The correct way of passing multiple hashes as arguments +---------------------------------------------------------------------------- +form_tag({:controller => "people", :action => "search"}, :method => "get") +# => <form action="/people/search" method="get"> +---------------------------------------------------------------------------- + +This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly. + +WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly `expecting tASSOC` syntax error. + +Checkboxes, radio buttons and other controls +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Checkboxes are form controls that give the user a set of options they can enable or disable: + +---------------------------------------------------------------------------- +<%= check_box_tag(:pet_dog) %> + <%= label_tag(:pet_dog, "I own a dog") %> +<%= check_box_tag(:pet_cat) %> + <%= label_tag(:pet_cat, "I own a cat") %> + +output: + +<input id="pet_dog" name="pet_dog" type="checkbox" value="1" /> + <label for="pet_dog">I own a dog</label> +<input id="pet_cat" name="pet_cat" type="checkbox" value="1" /> + <label for="pet_cat">I own a cat</label> +---------------------------------------------------------------------------- + +Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (user can only pick one): + +---------------------------------------------------------------------------- +<%= radio_button_tag(:age, "child") %> + <%= label_tag(:age_child, "I am younger than 21") %> +<%= radio_button_tag(:age, "adult") %> + <%= label_tag(:age_adult, "I'm over 21") %> + +output: + +<input id="age_child" name="age" type="radio" value="child" /> + <label for="age_child">I am younger than 21</label> +<input id="age_adult" name="age" type="radio" value="adult" /> + <label for="age_adult">I'm over 21</label> +---------------------------------------------------------------------------- + +IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region. + +Other form controls we might mention are the text area, password input and hidden input: + +---------------------------------------------------------------------------- +<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %> +<%= password_field_tag(:password) %> +<%= hidden_field_tag(:parent_id, "5") %> + +output: + +<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea> +<input id="password" name="password" type="password" /> +<input id="parent_id" name="parent_id" type="hidden" value="5" /> +---------------------------------------------------------------------------- + +Hidden inputs are not shown to the user, but they hold data same as any textual input. Values inside them can be changed with JavaScript. + +TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating `filter_parameter_logging(:password)` in your ApplicationController. + +How do forms with PUT or DELETE methods work? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then? + +Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the _real_ method: + +---------------------------------------------------------------------------- +form_tag(search_path, :method => "put") + +output: + +<form action="/search" method="post"> + <div style="margin:0;padding:0"> + <input name="_method" type="hidden" value="put" /> + <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> + </div> + ... +---------------------------------------------------------------------------- + +When parsing POSTed data, Rails will take into account the special `"_method"` parameter and act as if the HTTP method was the one specified inside it ("PUT" in this example). + + +Forms that deal with model attributes +------------------------------------- + +When we're dealing with an actual model, we will use a different set of form helpers and have Rails take care of some details in the background. In the following examples we will handle an Article model. First, let us have the controller create one: + +.articles_controller.rb +---------------------------------------------------------------------------- +def new + @article = Article.new +end +---------------------------------------------------------------------------- + +Now we switch to the view. The first thing to remember is that we should use `form_for` helper instead of `form_tag`, and that we should pass the model name and object as arguments: + +.articles/new.html.erb +---------------------------------------------------------------------------- +<% form_for :article, @article, :url => { :action => "create" } do |f| %> + <%= f.text_field :title %> + <%= f.text_area :body, :size => "60x12" %> + <%= submit_tag "Create" %> +<% end %> +---------------------------------------------------------------------------- + +There are a few things to note here: + +1. `:article` is the name of the model and `@article` is our record. +2. The URL for the action attribute is passed as a parameter named `:url`. +3. The `form_for` method yields *a form builder* object (the `f` variable). +4. Methods to create form controls are called *on* the form builder object `f` and *without* the `"_tag"` suffix (so `text_field_tag` becomes `f.text_field`). + +The resulting HTML is: + +---------------------------------------------------------------------------- +<form action="/articles/create" method="post"> + <input id="article_title" name="article[title]" size="30" type="text" /> + <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea> + <input name="commit" type="submit" value="Create" /> +</form> +---------------------------------------------------------------------------- + +A nice thing about `f.text_field` and other helper methods is that they will pre-fill the form control with the value read from the corresponding attribute in the model. For example, if we created the article instance by supplying an initial value for the title in the controller: + +---------------------------------------------------------------------------- +@article = Article.new(:title => "Rails makes forms easy") +---------------------------------------------------------------------------- + +... the corresponding input will be rendered with a value: + +---------------------------------------------------------------------------- +<input id="post_title" name="post[title]" size="30" type="text" value="Rails makes forms easy" /> +---------------------------------------------------------------------------- + +Relying on record identification +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it *a resource*. + +When dealing with RESTful resources, our calls to `form_for` can get significantly easier if we rely on *record identification*. In short, we can just pass the model instance and have Rails figure out model name and the rest: + +---------------------------------------------------------------------------- +## Creating a new article +# long-style: +form_for(:article, @article, :url => articles_path) +# same thing, short-style (record identification gets used): +form_for(@article) + +## Editing an existing article +# long-style: +form_for(:article, @article, :url => article_path(@article), :method => "put") +# short-style: +form_for(@article) +---------------------------------------------------------------------------- + +Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`. + +WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly.
\ No newline at end of file diff --git a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt new file mode 100644 index 0000000000..2805e5629d --- /dev/null +++ b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt @@ -0,0 +1,348 @@ +Getting Started With Rails +========================== + +This guide covers getting up and running with Ruby on Rails. After reading it, you should be familiar with: + +* Installing Rails, creating a new Rails application, and connecting your application to a database +* Understanding the purpose of each folder in the Rails structure +* Creating a scaffold, and explain what it is creating and why you need each element +* The basics of model, view, and controller interaction +* The basics of HTTP and RESTful design + +== How to use this guide +This guide is designed for beginners who want to get started with a Rails application from scratch. It assumes that you have no prior experience using the framework. However, it is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. + +== What is Rails? +Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than other languages and frameworks. + +== Installing Rails + +`gem install rails` + +== Create a new Rails project + +We're going to create a Rails project called "blog", which is the project that we will build off of for this guide. + +From your terminal, type: + +`rails blog` + +This will create a folder in your working directory called "blog". Open up that folder and have a look at it. For the majority of this tutorial, we will live in the app/ folder, but here's a basic rundown on the function of each folder in a Rails app: + +[grid="all"] +`-----------`----------------------------------------------------------------------------------------------------------------------------- +File/Folder Purpose +------------------------------------------------------------------------------------------------------------------------------------------ +README This is a brief instruction manual for your application. Use it to tell others what it does, how to set it up, etc. +Rakefile +app/ Contains the controllers, models, and views for your application. We'll focus on the app folder in this guide +config/ Configure your application's runtime rules, routes, database, etc. +db/ Shows your current database schema, as well as the database migrations (we'll get into migrations shortly) +doc/ In-depth documentation for your application +lib/ Extended modules for your application (not covered in this guide) +log/ Application log files +public/ The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go +script/ Scripts provided by Rails to do recurring tasks, benchmarking, plugin installation, starting the console or the web server +test/ Unit tests, fixtures, etc. (not covered in this guide) +tmp/ Temporary files +vendor/ Plugins folder +------------------------------------------------------------------------------------------------------------------------------------------- + +=== Configure SQLite Database + +Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While it is not designed for a production environment, it works well for development and testing. Rails defaults to SQLite as the database adapter when creating a new project, but you can always change it later. + +Open up +config/database.yml+ and you'll see the following: + +-------------------------------------------------------------------- +# SQLite version 3.x +# gem install sqlite3-ruby (not necessary on OS X Leopard) +development: + adapter: sqlite3 + database: db/development.sqlite3 + timeout: 5000 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + adapter: sqlite3 + database: db/test.sqlite3 + timeout: 5000 + +production: + adapter: sqlite3 + database: db/production.sqlite3 + timeout: 5000 +-------------------------------------------------------------------- + +If you're not running OS X 10.5 or greater, you'll need to install the SQLite gem. Similar to installing Rails you just need to run: + +`gem install sqlite3-ruby` + +Because we're using SQLite, there's really nothing else you need to do to setup your database! + +=== Configure MySQL Database + +.MySQL Tip +******************************* +If you want to skip directly to using MySQL on your development machine, typing the following will get you setup with a MySQL configuration file that assumes MySQL is running locally and that the root password is blank: + +`rails blog -d mysql` + +You'll need to make sure you have MySQL up and running on your system with the correct permissions. MySQL installation and configuration is outside the scope of this document. +******************************* + +If you choose to use MySQL, your +config/database.yml+ will look a little different: + +-------------------------------------------------------------------- +# MySQL. Versions 4.1 and 5.0 are recommended. +# +# Install the MySQL driver: +# gem install mysql +# On Mac OS X: +# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql +# On Mac OS X Leopard: +# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config +# This sets the ARCHFLAGS environment variable to your native architecture +# On Windows: +# gem install mysql +# Choose the win32 build. +# Install MySQL and put its /bin directory on your path. +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.0/en/old-client.html +development: + adapter: mysql + encoding: utf8 + database: blog_development + username: root + password: + socket: /tmp/mysql.sock + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + adapter: mysql + encoding: utf8 + database: blog_test + username: root + password: + socket: /tmp/mysql.sock + +production: + adapter: mysql + encoding: utf8 + database: blog_production + username: root + password: + socket: /tmp/mysql.sock +---------------------------------------------------------------------- + +== Starting the web server +Rails comes bundled with the lightweight Webrick web server, which (like SQLite) works great in development mode, but is not designed for a production environment. If you install Mongrel with `gem install mongrel`, Rails will use the Mongrel web server as the default instead (recommended). +******************* +If you're interested in alternative web servers for development and/or production, check out mod_rails (a.k.a Passenger) +******************* +Rails lets you run in development, test, and production environments (you can also add an unlimited number of additional environments if necessary). In this guide, we're going to work with the development environment only, which is the default when starting the server. From the root of your application folder, simply type the following to startup the web server: + +`./script/server` + +This will start a process that allows you to connect to your application via a web browser on port 3000. Open up a browser to +http://localhost:3000/+ + +You can hit Ctrl+C anytime from the terminal to stop the web server. + +You should see the "Welcome Aboard" default Rails screen, and can click on the "About your application's environment" link to see a brief summary of your current configuration. If you've gotten this far, you're riding rails! Let's dive into the code! + +== Models, Views, and Controllers +Rails uses Model, View, Controller (MVC) architecture because it isolates business logic from the user interface, ensuring that changes to a template will not affect the underlying code that makes it function. It also helps keep your code clean and DRY (Don't Repeat Yourself!) by making it perfectly clear where different types of code belong. + +=== The Model +The model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. Assume that for every table in your database, you will have a corresponding model (not necessarily the other way around, but that's beyond the scope of this guide). + +Models in Rails use a singular name, and their corresponding database tables use a plural name. In the case of our "Blog" application, we're going to need a table for our blog posts. Because we're generating a model, we want to use the singular name: + +`./script/generate model Post` + +You'll see that this generates several files, we're going to focus on two. First, let's take a look at +app/models/post.rb+ + +------------------------------- +class Post < ActiveRecord::Base +end +------------------------------- + +This is what each model you create will look like by default. Here Rails is making the assumption that your Post model will be tied to a database, because it is telling the Post class to descend from the ActiveRecord::Base class, which is where all the database magic happens. Let's leave the model alone for now and move onto migrations. + +==== Migrations +Database migrations make it simple to add/remove/modify tables, columns, and indexes while allowing you to roll back or forward between states with ease. + +Have a look at +db/migrate/2008XXXXXXXXXX_create_posts.rb+ (Yours will have numbers specific to the time that the file was generated), which was generated when creating our Post model: + +------------------------------------------- +class CreatePosts < ActiveRecord::Migration + def self.up + create_table :posts do |t| + + t.timestamps + end + end + + def self.down + drop_table :posts + end +end +------------------------------------------- + +By default, Rails creates a database migration that will create the table for "posts" (plural name of model). The +create_table+ method takes a ruby block, and by default you'll see +t.timestamps+ in there, which automatically creates and automatically handles +created_at+ and +updated_at+ datetime columns. The +self.up+ section handles progression of the database, whereas the +self.down+ handles regression (or rollback) of the migration. + +Let's add some more columns to our migration that suit our post table. We'll create a +name+ column for the person who wrote the post, a +title+ column for the title of the post, and a +content+ column for the actual post content. + +------------------------------------------- +class CreatePosts < ActiveRecord::Migration + def self.up + create_table :posts do |t| + t.string :name + t.string :title + t.text :content + t.timestamps + end + end + + def self.down + drop_table :posts + end +end +------------------------------------------- + +Now that we have our migration just right, we can run the migration (the +self.up+ portion) by returning to the terminal and running: + +`rake db:migrate` + +This command will always run any migrations that have not yet been run. + +.Singular and Plural Inflections +************************************************************************************************************** +Rails is very smart, it knows that if you have a model "Person," the database table should be called "people". If you have a model "Company", the database table will be called "companies". There are a few circumstances where it will not know the correct singular and plural of a model name, but you should have no problem with this as long as you are using common English words. Fixing these rare circumstances is beyond the scope of this guide. +************************************************************************************************************** + +=== The Controller +The controller communicates input from the user (the view) to the model. + +==== RESTful Design +The REST idea will likely take some time to wrap your brain around if you're new to the concept. But know the following: + +* It is best to keep your controllers RESTful at all times if possible +* Resources must be defined in +config/routes.rb+ in order for the RESTful architecture to work properly, so let's add that now: + +-------------------- +map.resources :posts +-------------------- + +* The seven actions that are automatically part of the RESTful design in Rails are +index+, +show+, +new+, +create+, +edit+, +update+, and +destroy+. + +Let's generate a controller: + +`./script/generate controller Posts` + +Open up the controller that it generates in +app/controllers/posts_controller.rb+. It should look like: + +--------------------------------------------- +class PostsController < ApplicationController +end +--------------------------------------------- + +Because of the +map.resources :posts+ line in your +config/routes.rb+ file, this controller is ready to take on all seven actions listed above. But we're going to need some logic in this controller in order to interact with the model, and we're going to need to generate our view files so the user can interact with your application from their browser. + +We're going to use the scaffold generator to create all the files and basic logic to make this work, now that you know how to generate models and controllers manually. + +To do that, let's completely start over. Back out of your Rails project folder, and *remove it completely* (`rm -rf blog`). +Create the project again and enter the directory by running the commands: + +`rails blog` + +`cd blog` + + +=== Rails Scaffold +Whenever you are dealing with a resource and you know you'll need a way to manage that resource in your application, you can start by generating a scaffold. The reason that this guide did not start with generating the scaffold is because it is not all that useful once you are using Rails on a regular basis. For our blog, we want a "Post" resource, so let's generate that now: + +`./script/generate scaffold Post name:string title:string content:text` + +This generates the model, controller, migration, views, tests, and routes for this resource. It also populates these files with default data to get started. + +First, let's make sure our database is up to date by running `rake db:migrate`. That may generate an error if your database still has the tables from our earlier migration. In this case, let's completely reset the database and run all migrations by running `rake db:reset`. + +Start up the web server with `./script/server` and point your browser to `http://localhost:3000/posts`. + +Here you'll see an example of the instant gratification of Rails where you can completely manage the Post resource. You'll be able to create, edit, and delete blog posts with ease. Go ahead, try it out. + +Now let's see how all this works. Open up `app/controllers/posts_controller.rb`, and you'll see this time it is filled with code. + +==== Index + +Let's take a look at the `index` action: + +----------------------------------------- +def index + @posts = Post.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @posts } + end +end +----------------------------------------- + +In this action, we're setting the `@posts` instance variable to a hash of all posts in the database. `Post.find(:all)` or `Post.all` (in Rails 2.1) calls on our model to return all the Posts in the database with no additional conditions. + +The `respond_to` block handles both HTML and XML calls to this action. If we call `http://localhost:3000/posts.xml`, we'll see all our posts in XML format. The HTML format looks for our corresponding view in `app/views/posts/index.html.erb`. You can add any number of formats to this block to allow actions to be processed with different file types. + +==== Show + +Back in your browser, click on the "New post" link and create your first post if you haven't done so already. Return back to the index, and you'll see the details of your post listed, along with three actions to the right of the post: `show`, `edit`, and `destroy`. Click the `show` link, which will bring you to the URL `http://localhost:3000/posts/1`. Now let's look at the `show` action in `app/controllers/posts_controller.rb`: + +----------------------------------------- +def show + @post = Post.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @post } + end +end +----------------------------------------- + +This time, we're setting `@post` to a single record in the database that is searched for by its `id`, which is provided to the controller by the "1" in `http://localhost:3000/posts/1`. The `show` action is ready to handle HTML or XML with the `respond_to` block: XML can be accessed at: `http://localhost:3000/posts/1.xml`. + +==== New & Create + +Description of new and create actions + +==== Edit & Update + +For the `edit`, `update`, and `destroy` actions, we will use the same `@post = Post.find(params[:id])` to find the appropriate record. + +==== Destroy + +Description of the destroy action + +=== The View +The view is where you put all the code that gets seen by the user: divs, tables, text, checkboxes, etc. Think of the view as the home of your HTML. If done correctly, there should be no business logic in the view. + + + + + + + + + + + + + + + + + diff --git a/railties/doc/guides/index.txt b/railties/doc/guides/index.txt new file mode 100644 index 0000000000..87d6804ead --- /dev/null +++ b/railties/doc/guides/index.txt @@ -0,0 +1,53 @@ +Ruby on Rails guides +==================== + +.link:getting_started_with_rails/getting_started_with_rails.html[Getting Started with Rails] +*********************************************************** +TODO: Insert some description here. +*********************************************************** + +.link:activerecord/association_basics.html[Active Record Associations] +*********************************************************** +Introduction to Active Record associations. +*********************************************************** + +.link:migrations/migrations.html[Rails Database Migrations] +*********************************************************** +TODO: Insert some description here. +*********************************************************** + +.link:forms/form_helpers.html[Action View Form Helpers] +*********************************************************** +Guide to using built in Form helpers. +*********************************************************** + +.link:testing_rails_applications/testing_rails_applications.html[Testing Rails Applications] +*********************************************************** +This is a rather comprehensive guide to doing both unit and functional tests +in Rails. It covers everything from ``What is a test?'' to the testing APIs. +Enjoy. +*********************************************************** + +.link:securing_rails_applications/securing_rails_applications.html[Securing Rails Applications] +*********************************************************** +This manual describes common security problems in web applications and how to +avoid them with Rails. +*********************************************************** + +.link:routing/routing_outside_in.html[Rails Routing from the Outside In] +*********************************************************** +This guide covers the user-facing features of Rails routing. If you want to +understand how to use routing in your own Rails applications, start here. +*********************************************************** + +.link:debugging/debugging_rails_applications.html[Debugging Rails Applications] +*********************************************************** +This guide describes how to debug Rails applications. It covers the different +ways of achieving this and how to understand what is happening "behind the scenes" +of your code. +*********************************************************** + +.link:creating_plugins/creating_plugins.html[The Basics of Creating Rails Plugins] +*********************************************************** +TODO: Insert some description here. +*********************************************************** diff --git a/railties/doc/guides/migrations/anatomy_of_a_migration.txt b/railties/doc/guides/migrations/anatomy_of_a_migration.txt new file mode 100644 index 0000000000..9f325af914 --- /dev/null +++ b/railties/doc/guides/migrations/anatomy_of_a_migration.txt @@ -0,0 +1,85 @@ +== Anatomy Of A Migration == + +Before I dive into the details of a migration, here are a few examples of the sorts of things you can do: + +[source, ruby] +------------------------ +class CreateProducts < ActiveRecord::Migration + def self.up + create_table :products do |t| + t.string :name + t.text :description + + t.timestamps + end + end + + def self.down + drop_table :products + end +end +------------------------ + +This migration adds a table called `products` with a string column called `name` and a text column called `description`. A primary key column called `id` will also be added, however since this is the default we do not need to ask for this. The timestamp columns `created_at` and `updated_at` which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table. + +Migrations are not limited to changing the schema. You can also use them to fix bad data in the database or populate new fields: + +[source, ruby] +------------------------ +class AddReceiveNewsletterToUsers < ActiveRecord::Migration + def self.up + change_table :users do |t| + t.boolean :receive_newsletter, :default => false + end + User.update_all ["receive_newsletter = ?", true] + end + + def self.down + remove_column :users, :receive_newsletter + end +end +------------------------ + +This migration adds an `receive_newsletter` column to the `users` table. We want it to default to `false` for new users, but existing users are considered +to have already opted in, so we use the User model to set the flag to `true` for existing users. + +NOTE: Some <<models,caveats>> apply to using models in your migrations. + +=== Migrations are classes +A migration is a subclass of ActiveRecord::Migration that implements two class methods: +up+ (perform the required transformations) and +down+ (revert them). + +Active Record provides methods that perform common data definition tasks in a database independent way (you'll read about them in detail later): + +* `create_table` +* `change_table` +* `drop_table` +* `add_column` +* `remove_column` +* `change_column` +* `rename_column` +* `add_index` +* `remove_index` + +If you need to perform tasks specific to your database (for example create a <<foreign_key,foreign key>> constraint) then the `execute` function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could +write code to set the value of that column for existing records (if necessary using your models). + +On databases that support transactions with statements that change the schema (such as PostgreSQL), migrations are wrapped in a transaction. If the database does not support this (for example MySQL and SQLite) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand. + +=== What's in a name === + +Migrations are stored in files in `db/migrate`, one for each migration class. The name of the file is of the form `YYYYMMDDHHMMSS_create_products.rb`, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The migration class' name must match (the camelcased version of) the latter part of the file name. For example `20080906120000_create_products.rb` should define CreateProducts and `20080906120001_add_details_to_products.rb` should define AddDetailsToProducts. If you do feel the need to change the file name then you MUST update the name of the class inside or Rails will complain about a missing class. + +Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by setting `config.active_record.timestamped_migrations` to `false` in `environment.rb`. + +The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers. + +For example Alice adds migrations `20080906120000` and `20080906123000` and Bob adds `20080906124500` and runs it. Alice finishes her changes and checks in her migrations and Bob pulls down the latest changes. Rails knows that it has not run Alice's two migrations so `rake db:migrate` would run them (even though Bob's migration with a later timestamp has been run), and similarly migrating down would not run their down methods. + +Of course this is no substitution for communication within the team, for example if Alice's migration removed a table that Bob's migration assumed the existence of then trouble will still occur. + +=== Changing migrations === + +Occasionally you will make a mistake while writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run `rake db:migrate`. You must rollback the migration (for example with `rake db:rollback`), edit your migration and then run `rake db:migrate` to run the corrected version. + +In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or more generally which has not been propagated beyond your development machine) is relatively harmless. Just use some common sense. + diff --git a/railties/doc/guides/migrations/creating_a_migration.txt b/railties/doc/guides/migrations/creating_a_migration.txt new file mode 100644 index 0000000000..892c73a533 --- /dev/null +++ b/railties/doc/guides/migrations/creating_a_migration.txt @@ -0,0 +1,109 @@ +== Creating A Migration == + +=== Creating a model === + +The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running + +`ruby script/generate model Product name:string description:text` will create a migration that looks like this + +[source, ruby] +----------------------- +class CreateProducts < ActiveRecord::Migration + def self.up + create_table :products do |t| + t.string :name + t.text :description + + t.timestamps + end + end + + def self.down + drop_table :products + end +end +----------------------- + +You can append as many column name/type pairs as you want. By default `t.timestamps` (which creates the `updated_at` and `created_at` columns that +are automatically populated by Active Record) will be added for you. + +=== Creating a standalone migration === +If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator: + +`ruby script/generate migration AddPartNumberToProducts` + +This will create an empty but appropriately named migration: + +[source, ruby] +----------------------- +class AddPartNumberToProducts < ActiveRecord::Migration + def self.up + end + + def self.down + end +end +----------------------- + +If the migration name is of the form AddXXXToYYY or RemoveXXXFromY and is followed by a list of column names and types then a migration containing +the appropriate add and remove column statements will be created. + +`ruby script/generate migration AddPartNumberToProducts part_number:string` + +will generate + +[source, ruby] +----------------------- +class AddPartNumberToProducts < ActiveRecord::Migration + def self.up + add_column :products, :part_number, :string + end + + def self.down + remove_column :products, :part_number + end +end +----------------------- + +Similarly, + +`ruby script/generate migration RemovePartNumberFromProducts part_number:string` + +generates + +[source, ruby] +----------------------- +class RemovePartNumberFromProducts < ActiveRecord::Migration + def self.up + remove_column :products, :part_number + end + + def self.down + add_column :products, :part_number, :string + end +end +----------------------- + +You are not limited to one magically generated column, for example + +`ruby script/generate migration AddDetailsToProducts part_number:string price:decimal` + +generates + +[source, ruby] +----------------------- +class AddDetailsToProducts < ActiveRecord::Migration + def self.up + add_column :products, :part_number, :string + add_column :products, :price, :decimal + end + + def self.down + remove_column :products, :price + remove_column :products, :part_number + end +end +----------------------- + +As always, what has been generated for you is just a starting point. You can add or remove from it as you see fit. + diff --git a/railties/doc/guides/migrations/foreign_keys.txt b/railties/doc/guides/migrations/foreign_keys.txt new file mode 100644 index 0000000000..c1cde64096 --- /dev/null +++ b/railties/doc/guides/migrations/foreign_keys.txt @@ -0,0 +1,7 @@ +[[foreign_key]] +== Active Record and Referential Integrity == +The Active Record way is that intelligence belongs in your models, not in the database. As such features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used. + +Validations such as `validates_uniqueness_of` are one way in which models can enforce data integrity. The `:dependent` option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints. + +Although Active Record does not provide any tools for working directly with such features, the `execute` method can be used to execute arbitrary SQL. There are also a number of plugins such as http://agilewebdevelopment.com/plugins/search?search=redhillonrails[redhillonrails] which add foreign key support to Active Record (including support for dumping foreign keys in `schema.rb`).
\ No newline at end of file diff --git a/railties/doc/guides/migrations/migrations.txt b/railties/doc/guides/migrations/migrations.txt new file mode 100644 index 0000000000..bbb39d0ccb --- /dev/null +++ b/railties/doc/guides/migrations/migrations.txt @@ -0,0 +1,21 @@ +Migrations +========== + +Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run `rake db:migrate`. Active Record will work out which migrations should be run. + +Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production. + +You'll learn all about migrations including: + +* The generators you can use to create them +* The methods Active Record provides to manipulate your database +* The Rake tasks that manipulate them +* How they relate to `schema.rb` + +include::anatomy_of_a_migration.txt[] +include::creating_a_migration.txt[] +include::writing_a_migration.txt[] +include::rakeing_around.txt[] +include::using_models_in_migrations.txt[] +include::scheming.txt[] +include::foreign_keys.txt[]
\ No newline at end of file diff --git a/railties/doc/guides/migrations/rakeing_around.txt b/railties/doc/guides/migrations/rakeing_around.txt new file mode 100644 index 0000000000..1fcca0cf24 --- /dev/null +++ b/railties/doc/guides/migrations/rakeing_around.txt @@ -0,0 +1,111 @@ +== Running Migrations == + +Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be `db:migrate`. In its most basic form it just runs the `up` method for all the migrations that have not yet been run. If there are no such migrations it exits. + +If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The +version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run + +------------------------------------ +rake db:migrate VERSION=20080906120000 +------------------------------------ + +If this is greater than the current version (i.e. it is migrating upwards) this will run the `up` method on all migrations up to and including 20080906120000, if migrating downwards this will run the `down` method on all the migrations down to, but not including, 20080906120000. + +=== Rolling back === + +A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run + +------------------ +rake db:rollback +------------------ + +This will run the `down` method from the latest migration. If you need to undo several migrations you can provide a `STEP` parameter: + +------------------ +rake db:rollback STEP=3 +------------------ + +will run the `down` method fron the last 3 migrations. + +The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating back up again. As with the `db:rollback` task you can use the `STEP` parameter if you need to go more than one version back, for example + +------------------ +rake db:migrate:redo STEP=3 +------------------ + +Neither of these Rake tasks do anything you could not do with `db:migrate`, they are simply more convenient since you do not need to explicitly specify the version to migrate to. + +Lastly, the `db:reset` task will drop the database, recreate it and load the current schema into it. + +NOTE: This is not the same as running all the migrations - see the section on <<schema,schema.rb>>. + +=== Being Specific === + +If you need to run a specific migration up or down the `db:migrate:up` and `db:migrate:down` tasks will do that. Just specify the appropriate version and the corresponding migration will have its `up` or `down` method invoked, for example + +------------------ +rake db:migrate:up VERSION=20080906120000 +------------------ + +will run the `up` method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example `db:migrate:up VERSION=20080906120000` will do nothing if Active Record believes that 20080906120000 has already been run. + + +=== Being talkative === + +By default migrations tell you exactly what they're doing and how long it took. +A migration creating a table and adding an index might produce output like this +------------------------- +== 20080906170109 CreateProducts: migrating =================================== +-- create_table(:products) + -> 0.0021s +-- add_index(:products, :name) + -> 0.0026s +== 20080906170109 CreateProducts: migrated (0.0059s) ========================== +------------------------- +Several methods are provided that allow you to control all this: + +* `suppress_messages` suppresses any output generated by its block +* `say` outputs text (the second argument controls whether it is indented or not) +* `say_with_time` outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected. + +For example, this migration + +[source, ruby] +---------------------- +class CreateProducts < ActiveRecord::Migration + def self.up + suppress_messages do + create_table :products do |t| + t.string :name + t.text :description + t.timestamps + end + end + say "Created a table" + suppress_messages {add_index :products, :name} + say "and an index!", true + say_with_time 'Waiting for a while' do + sleep 10 + 250 + end + end + + def self.down + drop_table :products + end +end +---------------------- + +generates the following output +---------------------- +== 20080906170109 CreateProducts: migrating =================================== +-- Created a table + -> and an index! +-- Waiting for a while + -> 10.0001s + -> 250 rows +== 20080906170109 CreateProducts: migrated (10.0097s) ========================= +---------------------- + +If you just want Active Record to shut up then running `rake db:migrate VERBOSE=false` will suppress any output. + diff --git a/railties/doc/guides/migrations/scheming.txt b/railties/doc/guides/migrations/scheming.txt new file mode 100644 index 0000000000..ba4fea8fe3 --- /dev/null +++ b/railties/doc/guides/migrations/scheming.txt @@ -0,0 +1,47 @@ +== Schema dumping and you == +[[schema]] +=== What are schema files for? === +Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either `schema.rb` or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database. + +There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema. + +For example, this is how the test database is created: the current development database is dumped (either to `schema.rb` or `development.sql`) and then loaded into the test database. + +Schema files are also useful if want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest. + +=== Types of schema dumps === +There are two ways to dump the schema. This is set in `config/environment.rb` by the `config.active_record.schema_format` setting, which may be either `:sql` or `:ruby`. + +If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look at this file you'll find that it looks an awful lot like one very big migration: + +[source, ruby] +-------------------------------------- +ActiveRecord::Schema.define(:version => 20080906171750) do + create_table "authors", :force => true do |t| + t.string "name" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "products", :force => true do |t| + t.string "name" + t.text "description" + t.datetime "created_at" + t.datetime "updated_at" + t.string "part_number" + end +end +-------------------------------------- + +In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using `create_table`, `add_index` and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases. + +There is however a trade-off: `schema.rb` cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to `:sql`. + +Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the `db:structure:dump` Rake task) into `db/#\{RAILS_ENV\}_structure.sql`. For example for PostgreSQL the `pg_dump` utility is used and for MySQL this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside. + +By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it. + +=== Schema dumps and source control === + +Because they are the authoritative source for your database schema, it is strongly recommended that you check them into source control. + diff --git a/railties/doc/guides/migrations/using_models_in_migrations.txt b/railties/doc/guides/migrations/using_models_in_migrations.txt new file mode 100644 index 0000000000..35a4c6fdfd --- /dev/null +++ b/railties/doc/guides/migrations/using_models_in_migrations.txt @@ -0,0 +1,46 @@ +[[models]] +== Using Models In Your Migrations == +When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed. + +Consider for example a migration that uses the Product model to update a row in the corresponding table. Alice later updates the Product model, adding a new column and a validation on it. Bob comes back from holiday, updates the source and runs outstanding migrations with `rake db:migrate`, including the one that used the Product model. When the migration runs the source is up to date and so the Product model has the validation added by Alice. The database however is still old and so does not have that column and an error ensues because that validation is on a column that does not yet exist. + +Frequently I just want to update rows in the database without writing out the SQL by hand: I'm not using anything specific to the model. One pattern for this is to define a copy of the model inside the migration itself, for example: + +[source, ruby] +------------------------- +class AddPartNumberToProducts < ActiveRecord::Migration + class Product < ActiveRecord::Base + end + + def self.up + ... + end + + def self.down + ... + end +end +------------------------- +The migration has its own minimal copy of the Product model and no longer cares about the Product model defined in the application. + +=== Dealing with changing models === + +For performance reasons information about the columns a model has is cached. For example if you add a column to a table and then try and use the corresponding model to insert a new row it may try and use the old column information. You can force Active Record to re-read the column information with the `reset_column_information` method, for example + +[source, ruby] +------------------------- +class AddPartNumberToProducts < ActiveRecord::Migration + class Product < ActiveRecord::Base + end + + def self.up + add_column :product, :part_number, :string + Product.reset_column_information + ... + end + + def self.down + ... + end +end +------------------------- diff --git a/railties/doc/guides/migrations/writing_a_migration.txt b/railties/doc/guides/migrations/writing_a_migration.txt new file mode 100644 index 0000000000..0ab5397a84 --- /dev/null +++ b/railties/doc/guides/migrations/writing_a_migration.txt @@ -0,0 +1,159 @@ +== Writing a Migration == + +Once you have created your migration using one of the generators it's time to get to work! + +=== Creating a table === + +`create_table` will be one of your workhorses. A typical use would be + +[source, ruby] +--------------------- +create_table :products do |t| + t.string :name +end +--------------------- +which creates a `products` table with a column called `name` (and as discussed below, an implicit `id` column). + +The object yielded to the block allows you create columns on the table. There are two ways of doing this. The first looks like + +[source, ruby] +--------------------- +create_table :products do |t| + t.column :name, :string, :null => false +end +--------------------- + +the second form, the so called "sexy" migrations, drops the somewhat redundant column method. Instead, the `string`, `integer` etc. methods create a column of that type. Subsequent parameters are identical. + +[source, ruby] +--------------------- +create_table :products do |t| + t.string :name, :null => false +end +--------------------- + +By default `create_table` will create a primary key called `id`. You can change the name of the primary key with the `:primary_key` option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass `:id => false`. If you need to pass database specific options you can place an sql fragment in the `:options` option. For example + +[source, ruby] +--------------------- +create_table :products, :options => "ENGINE=InnoDB" do |t| + t.string :name, :null => false +end +--------------------- +Will append `ENGINE=InnoDB` to the sql used to create the table (this is Rails' default when using MySQL). + +The types Active Record supports are `:primary_key`, `:string`, `:text`, `:integer`, `:float`, `:decimal`, `:datetime`, `:timestamp`, `:time`, `:date`, `:binary`, `:boolean`. + +These will be mapped onto an appropriate underlying database type, for example with MySQL `:string` is mapped to `VARCHAR(255)`. You can create columns of +types not supported by Active Record when using the non sexy syntax, for example + +[source, ruby] +--------------------- +create_table :products do |t| + t.column :name, 'polygon', :null => false +end +--------------------- +This may however hinder portability to other databases. + +=== Changing tables === + +`create_table`'s close cousin is `change_table`. Used for changing existing tables, it is used in a similar fashion to `create_table` but the object yielded to the block knows more tricks. For example + +[source, ruby] +--------------------- +change_table :products do |t| + t.remove :description, :name + t.string :part_number + t.index :part_number + t.rename :upccode, :upc_code +end +--------------------- +removes the `description` column, creates a `part_number` column and adds an index on it. Finally it renames the `upccode` column. This is the same as doing + +[source, ruby] +--------------------- +remove_column :products, :description +remove_column :products, :name +add_column :products, :part_number, :string +add_index :products, :part_number +rename_column :products, :upccode, :upc_code +--------------------- + +You don't have to keep repeating the table name and it groups all the statements related to modifying one particular table. The individual transformation names are also shorter, for example `remove_column` becomes just `remove` and `add_index` becomes just `index`. + +=== Special helpers === + +Active Record provides some shortcuts for common functionality. It is for example very common to add both the `created_at` and `updated_at` columns and so there is a method that does exactly that: + +[source, ruby] +--------------------- +create_table :products do |t| + t.timestamps +end +--------------------- +will create a new products table with those two columns whereas + +[source, ruby] +--------------------- +change_table :products do |t| + t.timestamps +end +--------------------- +adds those columns to an existing table. + +The other helper is called `references` (also available as `belongs_to`). In its simplest form it just adds some readability + +[source, ruby] +--------------------- +create_table :products do |t| + t.references :category +end +--------------------- + +will create a `category_id` column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the `_id` for you. If you have polymorphic belongs_to associations then `references` will add both of the columns required: + +[source, ruby] +--------------------- +create_table :products do |t| + t.references :attachment, :polymorphic => {:default => 'Photo'} +end +--------------------- +will add an `attachment_id` column and a string `attachment_type` column with a default value of 'Photo'. + +NOTE: The `references` helper does not actually create foreign key constraints for you. You will need to use `execute` for that or a plugin that adds <<foreign_key,foreign key support>>. + +If the helpers provided by Active Record aren't enough you can use the `execute` function to execute arbitrary SQL. + +For more details and examples of individual methods check the API documentation, in particular the documentation for http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html[ActiveRecord::ConnectionAdapters::SchemaStatements] (which provides the methods available in the `up` and `down` methods), http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html[ActiveRecord::ConnectionAdapters::TableDefinition] (which provides the methods available on the object yielded by `create_table`) and http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/Table.html[ActiveRecord::ConnectionAdapters::Table] (which provides the methods available on the object yielded by `change_table`). + +=== Writing your down method === + +The `down` method of your migration should revert the transformations done by the `up` method. In other words the database should be unchanged if you do an `up` followed by a `down`. For example if you create a table in the up you should drop it in the `down` method. It is wise to do things in precisely the reverse order to in the `up` method. For example + +[source, ruby] +--------------------- +class ExampleMigration < ActiveRecord::Migration + + def self.up + create_table :products do |t| + t.references :category + end + #add a foreign key + execute "ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)" + + add_column :users, :home_page_url, :string + + rename_column :users, :email, :email_address + end + + def self.down + rename_column :users, :email_address, :email + remove_column :users, :home_page_url + execute "ALTER TABLE products DROP FOREIGN KEY fk_products_categories" + drop_table :products + end +end +--------------------- +Sometimes your migration will do something which is just plain irreversible, for example it might destroy some data. In cases like those when you can't reverse the migration you can raise IrreversibleMigration from your `down` method. If someone tries to revert your migration an error message will be +displayed saying that it can't be done. + diff --git a/railties/doc/guides/routing/routing_outside_in.txt b/railties/doc/guides/routing/routing_outside_in.txt new file mode 100644 index 0000000000..bc08b107cf --- /dev/null +++ b/railties/doc/guides/routing/routing_outside_in.txt @@ -0,0 +1,838 @@ +Rails Routing from the Outside In +================================= + +This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to: + +* Understand the purpose of routing +* Decipher the code in +routes.rb+ +* Construct your own routes, using either the classic hash style or the now-preferred RESTful style +* Identify how a route will map to a controller and action + +== The Dual Purpose of Routing + +Rails routing is a two-way piece of machinery - rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings. + +=== Connecting URLs to Code + +When your Rails application receives an incoming HTTP request, say + +------------------------------------------------------- +GET /patient/17 +------------------------------------------------------- + +the routing engine within Rails is the piece of code that dispatches the request to the appropriate spot in your application. In this case, the application would most likely end up running the +show+ action within the +patients+ controller, displaying the details of the patient whose ID is 17. + +=== Generating URLs from Code + +Routing also works in reverse. If your application contains this code: + +[source, ruby] +------------------------------------------------------- +@patient = Patient.find(17) +<%= link_to "Patient Record", patient_path(@patient) %> +------------------------------------------------------- + +Then the routing engine is the piece that translates that to a link to a URL such as +http://example.com/patient/17+. By using routing in this way, you can reduce the brittleness of your application as compared to one with hard-coded URLs, and make your code easier to read and understand. + +NOTE: Patient needs to be declared as a resource for this style of translation via a named route to be available. + +== Quick Tour of Routes.rb + +There are two components to routing in Rails: the routing engine itself, which is supplied as part of Rails, and the file +config/routes.rb+, which contains the actual routes that will be used by your application. Learning exactly what you can put in +routes.rb+ is the main topic of this guide, but before we dig in let's get a quick overview. + +=== Processing the File + +In format, +routes.rb+ is nothing more than one big block sent to +ActionController::Routing::Routes.draw+. Within this block, you can have comments, but it's likely that most of your content will be individual lines of code - each line being a route in your application. You'll find five main types of content in this file: + +* RESTful Routes +* Named Routes +* Nested Routes +* Regular Routes +* Default Routes + +Each of these types of route is covered in more detail later in this guide. + +The +routes.rb+ file is processed from top to bottom when a request comes in. The request will be dispatched to the first matching route. If there is no matching route, then Rails returns HTTP status 404 to the caller. + +=== RESTful Routes + +RESTful routes take advantage of the built-in REST orientation of Rails to wrap up a lot of routing information in a single declaration. A RESTful route looks like this: + +[source, ruby] +------------------------------------------------------- +map.resources :books +------------------------------------------------------- + +=== Named Routes + +Named routes give you very readable links in your code, as well as handling incoming requests. Here's a typical named route: + +[source, ruby] +------------------------------------------------------- +map.login '/login', :controller => 'sessions', :action => 'new' +------------------------------------------------------- + +=== Nested Routes + +Nested routes let you declare that one resource is contained within another resource. You'll see later on how this translates to URLs and paths in your code. For example, if your application includes parts, each of which belongs to an assembly, you might have this nested route declaration: + +[source, ruby] +------------------------------------------------------- +map.resources :assemblies do |assemblies| + assemblies.resources :parts +end +------------------------------------------------------- + +=== Regular Routes + +In many applications, you'll also see non-RESTful routing, which explicitly connects the parts of a URL to a particular action. For example, + +[source, ruby] +------------------------------------------------------- +map.connect 'parts/:number', :controller => 'inventory', :action => 'show' +------------------------------------------------------- + +=== Default Routes + +The default routes are a safety net that catch otherwise-unrouted requests. Many Rails applications will contain this pair of default routes: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +------------------------------------------------------- + +These default routes are automatically generated when you create a new Rails application. If you're using RESTful routing for everything in your application, you will probably want to remove them. But be sure you're not using the default routes before you remove them! + +== RESTful Routing: the Rails Default + +RESTful routing is the current standard for routing in Rails, and it's the one that you should prefer for new applications. It can take a little while to understand how RESTful routing works, but it's worth the effort; your code will be easier to read and you'll be working with Rails, rather than fighting against it, when you use this style of routing. + +=== What is REST? + +The foundation of RESTful routing is generally considered to be Roy Fielding's doctoral thesis, link:http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm[Architectural Styles and the Design of Network-based Software Architectures]. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes: + +* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources +* Transferring representations of the state of that resource between system components. + +For example, to a Rails application a request such as this: + ++DELETE /photos/17+ + +would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities. + +=== CRUD, Verbs, and Actions + +In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as + +[source, ruby] +------------------------------------------------------- +map.resources :photos +------------------------------------------------------- + +creates seven different routes in your application: + +[grid="all"] +`----------`---------------`-----------`--------`------------------------------------------- +HTTP verb URL controller action used for +-------------------------------------------------------------------------------------------- +GET /photos Photos index display a list of all photos +GET /photos/new Photos new return an HTML form for creating a new photo +POST /photos Photos create create a new photo +GET /photos/1 Photos show display a specific photo +GET /photos/1/edit Photos edit return an HTML form for editing a photo +PUT /photos/1 Photos update update a specific photo +DELETE /photos/1 Photos destroy delete a specific photo +-------------------------------------------------------------------------------------------- + +For the specific routes (those that reference just a single resource), the identifier for the resource will be available within the corresponding controller action as +params[:id]+. + +TIP: If you consistently use RESTful routes in your application, you should disable the default routes in +routes.rb+ so that Rails will enforce the mapping between HTTP verbs and routes. + +=== URLs and Paths + +Creating a RESTful route will also make available a pile of helpers within your application: + +* +photos_url+ and +photos_path+ map to the path for the index and create actions +* +new_photo_url+ and +new_photo_path+ map to the path for the new action +* +edit_photo_url+ and +edit_photo_path+ map to the path for the edit action +* +photo_url+ and +photo_path+ map to the path for the show, update, and destroy actions + +NOTE: Because routing makes use of the HTTP verb as well as the path in the request to dispatch requests, the seven routes generated by a RESTful routing entry only give rise to four pairs of helpers. + +In each case, the +_url+ helper generates a string containing the entire URL that the application will understand, while the +_path+ helper generates a string containing the relative path from the root of the application. For example: + +[source, ruby] +------------------------------------------------------- +photos_url # => "http://www.example.com/photos" +photos_path # => "/photos" +------------------------------------------------------- + +=== Singular Resources + +You can also apply RESTful routing to singleton resources within your application. In this case, you use +map.resource+ instead of +map.resources+ and the route generation is slightly different. For example, a routing entry of + +[source, ruby] +------------------------------------------------------- +map.resource :geocoder +------------------------------------------------------- + +creates seven different routes in your application: + +[grid="all"] +`----------`---------------`-----------`--------`------------------------------------------- +HTTP verb URL controller action used for +-------------------------------------------------------------------------------------------- +GET /geocoder/new Geocoders new return an HTML form for creating the new geocoder +POST /geocoder Geocoders create create the new geocoder +GET /geocoder Geocoders show display the one and only geocoder resource +GET /geocoder/edit Geocoders edit return an HTML form for editing the geocoder +PUT /geocoder Geocoders update update the one and only geocoder resource +DELETE /geocoder Geocoders destroy delete the geocoder resource +-------------------------------------------------------------------------------------------- + +NOTE: Even though the name of the resource is singular in +routes.rb+, the matching controller is still plural. + +A singular RESTful route generates an abbreviated set of helpers: + +* +new_geocoder_url+ and +new_geocoder_path+ map to the path for the new action +* +edit_geocoder_url+ and +edit_geocoder_path+ map to the path for the edit action +* +geocoder_url+ and +geocoder_path+ map to the path for the create, show, update, and destroy actions + +=== Customizing Resources + +Although the conventions of RESTful routing are likely to be sufficient for many applications, there are a number of ways to customize the way that RESTful routes work. These options include: + +* +:controller+ +* +:singular+ +* +:requirements+ +* +:conditions+ +* +:as+ +* +:path_names+ +* +:path_prefix+ +* +:name_prefix+ + +You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide. + +==== Using :controller + +The +:controller+ option lets you use a controller name that is different from the public-facing resource name. For example, this routing entry: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :controller => "images" +------------------------------------------------------- + +will recognize incoming URLs containing +photo+ but route the requests to the Images controller: + +[grid="all"] +`----------`---------------`-----------`--------`------------------------------------------- +HTTP verb URL controller action used for +-------------------------------------------------------------------------------------------- +GET /photos Images index display a list of all images +GET /photos/new Images new return an HTML form for creating a new image +POST /photos Images create create a new image +GET /photos/1 Images show display a specific image +GET /photos/1/edit Images edit return an HTML form for editing a image +PUT /photos/1 Images update update a specific image +DELETE /photos/1 Images destroy delete a specific image +-------------------------------------------------------------------------------------------- + +NOTE: The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get +photos_path+, +photos_new_path+, and so on. + +==== Using :singular + +If for some reason Rails isn't doing what you want in converting the plural resource name to a singular name in member routes, you can override its judgment with the +:singular+ option: + +[source, ruby] +------------------------------------------------------- +map.resources :teeth, :singular => "tooth" +------------------------------------------------------- + +TIP: Depending on the other code in your application, you may prefer to add additional rules to the +Inflector+ class instead. + +==== Using :requirements + +You an use the +:requirements+ option in a RESTful route to impose a format on the implied +:id+ parameter in the singular routes. For example: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :requirements => {:id => /[A-Z][A-Z][0-9]+/} +------------------------------------------------------- + +This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, +/photos/1+ would no longer be recognized by this route, but +/photos/RR27+ would. + +==== Using :conditions + +Conditions in Rails routing are currently used only to set the HTTP verb for individual routes. Although in theory you can set this for RESTful routes, in practice there is no good reason to do so. (You'll learn more about conditions in the discussion of classic routing later in this guide.) + +==== Using :as + +The +:as+ option lets you override the normal naming for the actual generated paths. For example: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :as => "images" +------------------------------------------------------- + +will recognize incoming URLs containing +image+ but route the requests to the Photos controller: + +[grid="all"] +`----------`---------------`-----------`--------`------------------------------------------- +HTTP verb URL controller action used for +-------------------------------------------------------------------------------------------- +GET /images Photos index display a list of all photos +GET /images/new Photos new return an HTML form for creating a new photo +POST /images Photos create create a new photo +GET /images/1 Photos show display a specific photo +GET /images/1/edit Photos edit return an HTML form for editing a photo +PUT /images/1 Photos update update a specific photo +DELETE /images/1 Photos destroy delete a specific photo +-------------------------------------------------------------------------------------------- + +NOTE: The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get +photos_path+, +photos_new_path+, and so on. + +==== Using :path_names + +The +:path_names+ option lets you override the automatically-generated "new" and "edit" segments in URLs: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :path_names => { :new => 'make', :edit => 'change' } +------------------------------------------------------- + +This would cause the routing to recognize URLs such as + +------------------------------------------------------- +/photos/make +/photos/1/change +------------------------------------------------------- + +NOTE: The actual action names aren't changed by this option; the two URLs show would still route to the new and edit actions. + +TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can set a default in your environment: + +[source, ruby] +------------------------------------------------------- +config.action_controller.resources_path_names = { :new => 'make', :edit => 'change' } +------------------------------------------------------- + +==== Using :path_prefix + +The +:path_prefix+ option lets you add additional parameters that will be prefixed to the recognized paths. For example, suppose each photo in your application belongs to a particular photographer. In that case, you might declare this route: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :path_prefix => '/photographers/:photographer_id' +------------------------------------------------------- + +Routes recognized by this entry would include: + +------------------------------------------------------- +/photographers/1/photos/2 +/photographers/1/photos +------------------------------------------------------- + +NOTE: In most cases, it's simpler to recognize URLs of this sort by creating nested resources, as discussed in the next section. + +==== Using :name_prefix + +You can use the :name_prefix option to avoid collisions between routes. This is most useful when you have two resources with the same name that use +:path_prefix+ to map differently. For example: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :path_prefix => '/photographers/:photographer_id', :name_prefix => 'photographer_' +map.resources :photos, :path_prefix => '/agencies/:agency_id', :name_prefix => 'agency_' +------------------------------------------------------- + +This combination will give you route helpers such as +photographer_photos_path+ and +agency_photo_edit_path+ to use in your code. + +=== Nested Resources + +It's common to have resources that are logically children of other resources. For example, suppose your application includes these models: + +[source, ruby] +------------------------------------------------------- +class Magazine < ActiveRecord::Base + has_many :ads +end + +class Ad < ActiveRecord::Base + belongs_to :magazine +end +------------------------------------------------------- + +Each ad is logically subservient to one magazine. Nested routes allow you to capture this relationship in your routing. In this case, you might include this route declaration: + +[source, ruby] +------------------------------------------------------- +map.resources :magazines do |magazine| + magazine.resources :ads +end +------------------------------------------------------- + +In addition to the routes for magazines, this declaration will also create routes for ads, each of which requires the specification of a magazine in the URL: + +[grid="all"] +`----------`-----------------------`-----------`--------`------------------------------------------- +HTTP verb URL controller action used for +-------------------------------------------------------------------------------------------- +GET /magazines/1/ads Ads index display a list of all ads for a specific magazine +GET /magazines/1/ads/new Ads new return an HTML form for creating a new ad belonging to a specific magazine +POST /magazines/1/ads Ads create create a new photo belonging to a specific magazine +GET /magazines/1/ads/1 Ads show display a specific photo belonging to a specific magazine +GET /magazines/1/ads/1/edit Ads edit return an HTML form for editing a photo belonging to a specific magazine +PUT /magazines/1/ads/1 Ads update update a specific photo belonging to a specific magazine +DELETE /magazines/1/ads/1 Ads destroy delete a specific photo belonging to a specific magazine +-------------------------------------------------------------------------------------------- + +This will also create routing helpers such as +magazine_ads_url+ and +magazine_edit_ad_path+. + +==== Using :name_prefix + +The +:name_prefix+ option overrides the automatically-generated prefix in nested route helpers. For example, + +[source, ruby] +------------------------------------------------------- +map.resources :magazines do |magazine| + magazine.resources :ads, :name_prefix => 'periodical' +end +------------------------------------------------------- + +This will create routing helpers such as +periodical_ads_url+ and +periodical_edit_ad_path+. You can even use +:name_prefix+ to suppress the prefix entirely: + +[source, ruby] +------------------------------------------------------- +map.resources :magazines do |magazine| + magazine.resources :ads, :name_prefix => nil +end +------------------------------------------------------- + +This will create routing helpers such as +ads_url+ and +edit_ad_path+. Note that calling these will still require supplying an article id: + +[source, ruby] +------------------------------------------------------- +ads_url(@magazine) +edit_ad_path(@magazine, @ad) +------------------------------------------------------- + +==== Using :has_one and :has_many + +The +:has_one+ and +:has_many+ options provide a succinct notation for simple nested routes. Use +:has_one+ to nest a singleton resource, or +:has_many+ to nest a plural resource: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :has_one => :photographer, :has_many => [:publications, :versions] +------------------------------------------------------- + +This has the same effect as this set of declarations: + +[source, ruby] +------------------------------------------------------- +map.resources :photos do |photo| + photo.resource :photographer + photo.resources :publications + photo.resources :versions +end +------------------------------------------------------- + +==== Limits to Nesting + +You can nest resources within other nested resources if you like. For example: + +[source, ruby] +------------------------------------------------------- +map.resources :publishers do |publisher| + publisher.resources :magazines do |magazine| + magazine.resources :photos + end +end +------------------------------------------------------- + +However, without the use of +name_prefix => nil+, deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize URLs such as + +------------------------------------------------------- +/publishers/1/magazines/2/photos/3 +------------------------------------------------------- + +The corresponding route helper would be +publisher_magazine_photo_url+, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular link:http://weblog.jamisbuck.org/2007/2/5/nesting-resources[article] by Jamis Buck proposes a rule of thumb for good Rails design: + +_Resources should never be nested more than 1 level deep._ + +==== Shallow Nesting + +The +:shallow+ option provides an elegant solution to the difficulties of deeply-nested routes. If you specify this option at any level of routing, then paths for nested resources which reference a specific member (that is, those with an +:id+ parameter) will not use the parent path prefix or name prefix. To see what this means, consider this set of routes: + +[source, ruby] +------------------------------------------------------- +map.resources :publishers, :shallow => true do |publisher| + publisher.resources :magazines do |magazine| + magazine.resources :photos + end +end +------------------------------------------------------- + +This will enable recognition of (among others) these routes: + +------------------------------------------------------- +/publishers/1 ==> publisher_path(1) +/publishers/1/magazines ==> publisher_magazines_path(1) +/magazines/2 ==> magazine_path(2) +/magazines/2/photos ==> magazines_photos_path(2) +/photos/3 ==> photo_path(3) +------------------------------------------------------- + +With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you _can_ supply more information. All of the nested routes continue to work, just as they would without shallow nesting, but less-deeply nested routes (even direct routes) work as well. So, with the declaration above, all of these routes refer to the same resource: + +------------------------------------------------------- +/publishers/1/magazines/2/photos/3 ==> publisher_magazine_photo_path(1,2,3) +/magazines/2/photos/3 ==> magazine_photo_path(2,3) +/photos/3 ==> photo_path(3) +------------------------------------------------------- + +Shallow nesting gives you the flexibility to use the shorter direct routes when you like, while still preserving the longer nested routes for times when they add code clarity. + +If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options: + +[source, ruby] +------------------------------------------------------- +map.resources :publishers, :has_many => { :magazines => :photos }, :shallow => true +------------------------------------------------------- + +=== Adding More RESTful Actions + +You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional member routes (those which apply to a single instance of the resource), additional new routes (those that apply to creating a new resource), or additional collection routes (those which apply to the collection of resources as a whole). + +==== Adding Member Routes + +To add a member route, use the +:member+ option: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :member => { :preview => :get } +------------------------------------------------------- + +This will enable Rails to recognize URLs such as +/photos/1/preview+ using the GET HTTP verb, and route them to the preview action of the Photos controller. It will also create a +preview_photo+ route helper. + +Within the hash of member routes, each route name specifies the HTTP verb that it will recognize. You can use +:get+, +:put+, +:post+, +:delete+, or +:any+ here. + +==== Adding Collection Routes + +To add a collection route, use the +:collection+ option: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :collection => { :search => :get } +------------------------------------------------------- + +This will enable Rails to recognize URLs such as +/photos/search+ using the GET HTTP verb, and route them to the search action of the Photos controller. It will also create a +search_photos+ route helper. + +==== Adding New Routes + +To add a new route (one that creates a new resource), use the +:new+ option: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :new => { :upload => :post } +------------------------------------------------------- + +This will enable Rails to recognize URLs such as +/photos/upload+ using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create a +upload_photos+ route helper. + +TIP: If you want to redefine the verbs accepted by one of the standard actions, you can do so by explicitly mapping that action. For example: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :new => { :new => :any } +------------------------------------------------------- + +This will allow the new action to be invoked by any request to +photos/new+, no matter what HTTP verb you use. + +==== A Note of Caution + +If you find yourself adding many extra actions to a RESTful route, it's time to stop and ask yourself whether you're disguising the presence of another resource that would be better split off on its own. When the +:member+ and +:collection+ hashes become a dumping-ground, RESTful routes lose the advantage of easy readability that is one of their strongest points. + +== Regular Routes + +In addition to RESTful routing, Rails supports regular routing - a way to map URLs to controllers and actions. With regular routing, you don't get the masses of routes automatically generated by RESTful routing. Instead, you must set up each route within your application separately. + +While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing _when possible_, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit. + +=== Bound Parameters + +When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: +:controller+ maps to the name of a controller in your application, and +:action+ maps to the name of an action within that controller. For example, consider one of the default Rails routes: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id' +------------------------------------------------------- + +If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +Photos+ controller, and to make the final parameter (1) available as +params[:id]+. + +=== Wildcard Components + +You can set up as many wildcard symbols within a regular route as you like. Anything other than +:controller+ or +:action+ will be available to the matching action as part of the params hash. So, if you set up this route: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id/:userid:' +------------------------------------------------------- + +An incoming URL of +/photos/show/1/2+ will be dispatched to the +show+ action of the +Photos+ controller. +params[:id]+ will be set to 1, and +params[:user_id]+ will be set to 2. + +=== Static Text + +You can specify static text when creating a route. In this case, the static text is used only for matching the incoming requests: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id/with_user/:userid:' +------------------------------------------------------- + +This route would respond to URLs such as +/photos/show/1/with_user/2+. + +=== Querystring Parameters + +Rails routing automatically picks up querystring parameters and makes them available in the +params+ hash. For example, with this route: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id' +------------------------------------------------------- + +An incoming URL of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params[:id]+ will be set to 1, and +params[:user_id]+ will be equal to 2. + +=== Defining Defaults + +You do not need to explicitly use the +:controller+ and +:action+ symbols within a route. You can supply defaults for these two parameters in a hash: + +[source, ruby] +------------------------------------------------------- +map.connect 'photo/:id', :controller => 'photos', :action => 'show' +------------------------------------------------------- + +With this route, an incoming URL of +/photos/12+ would be dispatched to the +show+ action within the +Photos+ controller. + +=== Named Routes + +Regular routes need not use the +connect+ method. You can use any other name here to create a _named route_. For example, + +[source, ruby] +------------------------------------------------------- +map.logout '/logout', :controller => 'sessions', :action => 'destroy' +------------------------------------------------------- + +This will do two things. First, requests to +/logout+ will be sent to the +destroy+ method of the +Sessions+ controller. Second, Rails will maintain the +logout_path+ and +logout_url+ helpers for use within your code. + +=== Route Requirements + +You can use the +:requirements+ option to enforce a format for any parameter in a route: + +[source, ruby] +------------------------------------------------------- +map.connect 'photo/:id', :controller => 'photos', :action => 'show', + :requirements => { :id => /[A-Z]\d{5}/ } +------------------------------------------------------- + +This route would respond to URLs such as +/photo/A12345+. You can more succinctly express the same route this way: + +[source, ruby] +------------------------------------------------------- +map.connect 'photo/:id', :controller => 'photos', :action => 'show', + :id => /[A-Z]\d{5}/ +------------------------------------------------------- + +=== Route Conditions + +Route conditions (introduced with the +:conditions+ option) are designed to implement restrictions on routes. Currently, the only supported restriction is +:method+: + +[source, ruby] +------------------------------------------------------- +map.connect 'photo/:id', :controller => 'photos', :action => 'show', + :conditions => { :method => :get } +------------------------------------------------------- + +As with conditions in RESTful routes, you can specify +:get+, +:post+, +:put+, +:delete+, or +:any+ for the acceptable method. + +=== Route Globbing + +Route globbing is a way to specify that a particular parameter (which must be the last parameter in the route) should engulf all the remaining parts of a route. For example + +[source, ruby] +------------------------------------------------------- +map.connect 'photo/*other', :controller => 'photos', :action => 'unknown', +------------------------------------------------------- + +This route would match +photo/12+ or +/photo/long/path/to/12+ equally well, creating an array of path segments as the value of +params[:other]+. + +=== Route Options + +You can use +:with_options+ to simplify defining groups of similar routes: + +[source, ruby] +------------------------------------------------------- +map.with_options :controller => 'photo' do |photo| + photo.list '', :action => 'index' + photo.delete ':id/delete', :action => 'delete' + photo.edit ':id/edit', :action => 'edit' +end +------------------------------------------------------- + +The importance of +map.with_options+ has declined with the introduction of RESTful routes. + +== Formats and respond_to + +There's one more way in which routing can do different things depending on differences in the incoming HTTP request: by issuing a response that corresponds to what the request specifies that it will accept. In Rails routing, you can control this with the special +:format+ parameter in the route. + +For instance, consider the second of the default routes in the boilerplate +routes.rb+ file: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id.:format' +------------------------------------------------------- + +This route matches requests such as +/photo/new/1.xml+ or +/photo/show/2.rss+. Within the appropriate action code, you can issue different responses depending on the requested format: + +[source, ruby] +------------------------------------------------------- +respond_to do |format| + format.html # return the default template for HTML + format.xml { render :xml => @photo.to_xml } +end +------------------------------------------------------- + +=== Specifying the Format with an HTTP Header + +If there is no +:format+ parameter in the route, Rails will automatically look at the HTTP Accept header to determine the desired format. + +=== Recognized MIME types + +By default, Rails recognizes +html+, +text+, +json+, +csv+, +xml+, +rss+, +atom+, and +yaml+ as acceptable response types. If you need types beyond this, you can register them in your environment: + +[source, ruby] +------------------------------------------------------- +Mime::Type.register "image/jpg", :jpg +------------------------------------------------------- + +== The Default Routes + +When you create a new Rails application, +routes.rb+ is initialized with two default routes: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +------------------------------------------------------- + +These routes provide reasonable defaults for many URLs, if you're not using RESTful routing. + +NOTE: The default routes will make every action of every controller in your application accessible to GET requests. If you've designed your application to make consistent use of RESTful and named routes, you should comment out the default routes to prevent access to your controllers through the wrong verbs. If you've had the default routes enabled during development, though, you need to be sure that you haven't unwittingly depended on them somewhere in your application - otherwise you may find mysterious failures when you disable them. + +== The Empty Route + +Don't confuse the default routes with the empty route. The empty route has one specific purpose: to route requests that come in to the root of the web site. For example, if your site is example.com, then requests to +http://example.com+ or +http://example.com/+ will be handled by the empty route. + +=== Using map.root + +The preferred way to set up the empty route is with the +map.root+ command: + +[source, ruby] +------------------------------------------------------- +map.root :controller => "pages", :action => "main" +------------------------------------------------------- + +The use of the +root+ method tells Rails that this route applies to requests for the root of the site. + +For better readability, you can specify an already-created route in your call to +map.root+: + +[source, ruby] +------------------------------------------------------- +map.index :controller => "pages", :action => "main" +map.root :index +------------------------------------------------------- + +Because of the top-down processing of the file, the named route must be specified _before_ the call to +map.route+. + +=== Connecting the Empty String + +You can also specify an empty route by explicitly connecting the empty string: + +[source, ruby] +------------------------------------------------------- +map.connect '', :controller => "pages", :action => "main" +------------------------------------------------------- + +TIP: If the empty route does not seem to be working in your application, make sure that you have deleted the file +public/index.html+ from your Rails tree. + +== Inspecting and Testing Routes + +Routing in your application should not be a "black box" that you never open. Rails offers built-in tools for both inspecting and testing routes. + +=== Seeing Existing Routes with rake + +If you want a complete list of all of the available routes in your application, run the +rake routes+ command. This will dump all of your routes to the console, in the same order that they appear in +routes.rb+. For each route, you'll see: + +* The route name (if any) +* The HTTP verb used (if the route doesn't respond to all verbs) +* The URL pattern +* The routing parameters that will be generated by this URL + +For example, here's a small section of the +rake routes+ output for a RESTful route: + +------------------------------------------------------------------------------------------------------- + users GET /users {:controller=>"users", :action=>"index"} +formatted_users GET /users.:format {:controller=>"users", :action=>"index"} + POST /users {:controller=>"users", :action=>"create"} + POST /users.:format {:controller=>"users", :action=>"create"} +------------------------------------------------------------------------------------------------------- + +TIP: You'll find that the output from +rake routes+ is much more readable if you widen your terminal window until the output lines don't wrap. + +=== Testing Routes + +Routes should be included in your testing strategy (just like the rest of your application). Rails offers three link:http://api.rubyonrails.com/classes/ActionController/Assertions/RoutingAssertions.html[built-in assertions] designed to make testing routes simpler: + +* +assert_generates+ +* +assert_recognizes+ +* +assert_routing+ + +==== The +assert_generates+ Assertion + +Use +assert_generates+ to assert that a particular set of options generate a particular path. You can use this with default routes or custom routes + +[source, ruby] +------------------------------------------------------- +assert_generates "/photos/1", { :controller => "photos", :action => "show", :id => "1" } +assert_generates "/about", :controller => "pages", :action => "about" +------------------------------------------------------- + +==== The +assert_recognizes+ Assertion + +The +assert_recognizes+ assertion is the inverse of +assert_generates+. It asserts that Rails recognizes the given path and routes it to a particular spot in your application. + +[source, ruby] +------------------------------------------------------- +assert_recognizes { :controller => "photos", :action => "show", :id => "1" }, "/photos/1" +------------------------------------------------------- + +You can supply a +:method+ argument to specify the HTTP verb: + +[source, ruby] +------------------------------------------------------- +assert_recognizes { :controller => "photos", :action => "create" }, { :path => "photos", :method => :post } +------------------------------------------------------- + +You can also use the RESTful helpers to test recognition of a RESTful route: + +[source, ruby] +------------------------------------------------------- +assert_recognizes new_photo_url, { :path => "photos", :method => :post } +------------------------------------------------------- + +==== The +assert_routing+ Assertion + +The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+. + +[source, ruby] +------------------------------------------------------- +assert_routing { :path => "photos", :method => :post }, { :controller => "photos", :action => "create" } +-------------------------------------------------------
\ No newline at end of file |