From a17027d13a48e1e64b14a28e7d58e341812f8cb4 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 13 Sep 2008 20:28:01 +0100 Subject: Merge docrails --- .../doc/guides/activerecord/association_basics.txt | 1657 ++++++++++++++++++++ .../debugging/debugging_rails_applications.txt | 604 +++++++ railties/doc/guides/forms/form_helpers.txt | 270 ++++ .../getting_started_with_rails.txt | 348 ++++ railties/doc/guides/index.txt | 53 + .../guides/migrations/anatomy_of_a_migration.txt | 85 + .../doc/guides/migrations/creating_a_migration.txt | 109 ++ railties/doc/guides/migrations/foreign_keys.txt | 7 + railties/doc/guides/migrations/migrations.txt | 21 + railties/doc/guides/migrations/rakeing_around.txt | 111 ++ railties/doc/guides/migrations/scheming.txt | 47 + .../migrations/using_models_in_migrations.txt | 46 + .../doc/guides/migrations/writing_a_migration.txt | 159 ++ railties/doc/guides/routing/routing_outside_in.txt | 838 ++++++++++ 14 files changed, 4355 insertions(+) create mode 100644 railties/doc/guides/activerecord/association_basics.txt create mode 100644 railties/doc/guides/debugging/debugging_rails_applications.txt create mode 100644 railties/doc/guides/forms/form_helpers.txt create mode 100644 railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt create mode 100644 railties/doc/guides/index.txt create mode 100644 railties/doc/guides/migrations/anatomy_of_a_migration.txt create mode 100644 railties/doc/guides/migrations/creating_a_migration.txt create mode 100644 railties/doc/guides/migrations/foreign_keys.txt create mode 100644 railties/doc/guides/migrations/migrations.txt create mode 100644 railties/doc/guides/migrations/rakeing_around.txt create mode 100644 railties/doc/guides/migrations/scheming.txt create mode 100644 railties/doc/guides/migrations/using_models_in_migrations.txt create mode 100644 railties/doc/guides/migrations/writing_a_migration.txt create mode 100644 railties/doc/guides/routing/routing_outside_in.txt (limited to 'railties/doc') 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
-tag that has object dumped by YAML. Generating readable output to inspect any object.
+
+[source, html]
+----------------------------------------------------------------------------
+<%= debug @post %>
+

+ Title: + <%=h @post.title %> +

+---------------------------------------------------------------------------- + +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 %> +

+ Title: + <%=h @post.title %> +

+---------------------------------------------------------------------------- + +`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 %> +

+ Title: + <%=h @post.title %> +

+---------------------------------------------------------------------------- + +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 # +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 ' 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 ` 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 show constants of object +(rdb:1) v[ar] g[lobal] show global variables +(rdb:1) v[ar] i[nstance] 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.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ć + +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 contents +
+---------------------------------------------------------------------------- + +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 +---------------------------------------------------------------------------- +
+ + + +
+---------------------------------------------------------------------------- + +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") +# =>
+---------------------------------------------------------------------------- + +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") +# => +---------------------------------------------------------------------------- + +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: + + + + + +---------------------------------------------------------------------------- + +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: + + + + + +---------------------------------------------------------------------------- + +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: + + + + +---------------------------------------------------------------------------- + +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: + + +
+ + +
+ ... +---------------------------------------------------------------------------- + +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: + +---------------------------------------------------------------------------- + + + + +
+---------------------------------------------------------------------------- + +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: + +---------------------------------------------------------------------------- + +---------------------------------------------------------------------------- + +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 <> 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 <> 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 <>. + +=== 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 <>. + +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 -- cgit v1.2.3 From 118b0b607f98a6ac5e69355fdd65142c31ef6ec1 Mon Sep 17 00:00:00 2001 From: Tore Darell Date: Fri, 26 Sep 2008 22:56:50 +0200 Subject: Add ActionController guide (draft, unfinished) --- .../guides/actioncontroller/actioncontroller.txt | 28 +++++ railties/doc/guides/actioncontroller/cookies.txt | 26 +++++ railties/doc/guides/actioncontroller/filters.txt | 118 +++++++++++++++++++ railties/doc/guides/actioncontroller/http_auth.txt | 24 ++++ .../doc/guides/actioncontroller/introduction.txt | 7 ++ railties/doc/guides/actioncontroller/methods.txt | 37 ++++++ .../actioncontroller/parameter_filtering.txt | 14 +++ railties/doc/guides/actioncontroller/params.txt | 62 ++++++++++ .../actioncontroller/request_response_objects.txt | 35 ++++++ railties/doc/guides/actioncontroller/rescue.txt | 3 + railties/doc/guides/actioncontroller/session.txt | 130 +++++++++++++++++++++ railties/doc/guides/actioncontroller/streaming.txt | 91 +++++++++++++++ .../doc/guides/actioncontroller/verification.txt | 3 + 13 files changed, 578 insertions(+) create mode 100644 railties/doc/guides/actioncontroller/actioncontroller.txt create mode 100644 railties/doc/guides/actioncontroller/cookies.txt create mode 100644 railties/doc/guides/actioncontroller/filters.txt create mode 100644 railties/doc/guides/actioncontroller/http_auth.txt create mode 100644 railties/doc/guides/actioncontroller/introduction.txt create mode 100644 railties/doc/guides/actioncontroller/methods.txt create mode 100644 railties/doc/guides/actioncontroller/parameter_filtering.txt create mode 100644 railties/doc/guides/actioncontroller/params.txt create mode 100644 railties/doc/guides/actioncontroller/request_response_objects.txt create mode 100644 railties/doc/guides/actioncontroller/rescue.txt create mode 100644 railties/doc/guides/actioncontroller/session.txt create mode 100644 railties/doc/guides/actioncontroller/streaming.txt create mode 100644 railties/doc/guides/actioncontroller/verification.txt (limited to 'railties/doc') diff --git a/railties/doc/guides/actioncontroller/actioncontroller.txt b/railties/doc/guides/actioncontroller/actioncontroller.txt new file mode 100644 index 0000000000..c5a594d713 --- /dev/null +++ b/railties/doc/guides/actioncontroller/actioncontroller.txt @@ -0,0 +1,28 @@ +Action Controller basics +======================= + +In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request. + +include::introduction.txt[] + +include::methods.txt[] + +include::params.txt[] + +include::session.txt[] + +include::cookies.txt[] + +include::filters.txt[] + +include::request_response_objects.txt[] + +include::http_auth.txt[] + +include::streaming.txt[] + +include::parameter_filtering.txt[] + +include::verification.txt[] + +include::rescue.txt[] diff --git a/railties/doc/guides/actioncontroller/cookies.txt b/railties/doc/guides/actioncontroller/cookies.txt new file mode 100644 index 0000000000..dbcec23e45 --- /dev/null +++ b/railties/doc/guides/actioncontroller/cookies.txt @@ -0,0 +1,26 @@ +== Cookies == + +Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which - much like the `session` - works like a hash: + +TODO: Find a real-world example where cookies are used + +[code, ruby] +----------------------------------------- +class FooController < ApplicationController + + def foo + cookies[:foo] = "bar" + end + + def display_foo + @foo = cookies[:foo] + end + + def remove_foo + cookies.delete(:foo) + end + +end +----------------------------------------- + +Note that while for session values, you set the key to `nil`, to delete a cookie value, you use `cookies.delete(:key)`. diff --git a/railties/doc/guides/actioncontroller/filters.txt b/railties/doc/guides/actioncontroller/filters.txt new file mode 100644 index 0000000000..96078ea208 --- /dev/null +++ b/railties/doc/guides/actioncontroller/filters.txt @@ -0,0 +1,118 @@ +== Filters == + +Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first: + +[code, ruby] +--------------------------------- +class ApplicationController < ActionController::Base + +private + + def require_login + unless logged_in? + flash[:error] = "You must be logged in to access this section" + redirect_to new_login_url # Prevents the current action from running + end + end + + # The logged_in? method simply returns true if the user is logged in and + # false otherwise. It does this by "booleanizing" the current_user method + # we created previously using a double ! operator. Note that this is not + # common in Ruby and is discouraged unless you really mean to convert something + # into true or false. + def logged_in? + !!current_user + end + +end +--------------------------------- + +The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the "before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704 method: + +[code, ruby] +--------------------------------- +class ApplicationController < ActionController::Base + + before_filter :require_login + +end +--------------------------------- + +In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use "skip_before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711 : + +[code, ruby] +--------------------------------- +class LoginsController < Application + + skip_before_filter :require_login, :only => [:new, :create] + +end +--------------------------------- + +Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place. + +=== After filters and around filters === + +In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it. + +TODO: Find a real example for an around filter + +[code, ruby] +--------------------------------- +class ApplicationController < Application + + around_filter :foo + +private + + def foo + logger.debug("Action has not been run yet") + yield #Run the action + logger.debug("Action has been run") + end + +end +--------------------------------- + +=== Other types of filters === + +While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways. + +The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block: + +[code, ruby] +--------------------------------- +class ApplicationController < ActionController::Base + + before_filter { |controller| redirect_to new_login_url unless controller.send(:logged_in?) } + +end +--------------------------------- + +Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful. + +The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class: + +[code, ruby] +--------------------------------- +class ApplicationController < ActionController::Base + + before_filter LoginFilter + +end + +class LoginFilter + + def self.filter(controller) + unless logged_in? + controller.flash[:error] = "You must be logged in to access this section" + controller.redirect_to controller.new_login_url + end + end + +end +--------------------------------- + +Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action. + +The Rails API documentation has "more information and detail on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html diff --git a/railties/doc/guides/actioncontroller/http_auth.txt b/railties/doc/guides/actioncontroller/http_auth.txt new file mode 100644 index 0000000000..e3361609a9 --- /dev/null +++ b/railties/doc/guides/actioncontroller/http_auth.txt @@ -0,0 +1,24 @@ +== HTTP Basic Authentication == + +Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, "authenticate_or_request_with_http_basic":http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610 + +[code, ruby] +------------------------------------- +class AdminController < ApplicationController + + USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c" + + before_filter :authenticate + +private + + def authenticate + authenticate_or_request_with_http_basic do |username, password| + username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD + end + end + +end +------------------------------------- + +With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication. diff --git a/railties/doc/guides/actioncontroller/introduction.txt b/railties/doc/guides/actioncontroller/introduction.txt new file mode 100644 index 0000000000..35540bbc09 --- /dev/null +++ b/railties/doc/guides/actioncontroller/introduction.txt @@ -0,0 +1,7 @@ +== What does a controller do? == + +Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible. + +For most conventional RESTful applications, the controller will receive the request (this is invisible to the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work. + +A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model. diff --git a/railties/doc/guides/actioncontroller/methods.txt b/railties/doc/guides/actioncontroller/methods.txt new file mode 100644 index 0000000000..0818dbb849 --- /dev/null +++ b/railties/doc/guides/actioncontroller/methods.txt @@ -0,0 +1,37 @@ +== Methods and actions == + +A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) is run. + +[source, ruby] +---------------------------------------------- +class ClientsController < ActionController::Base + + # Actions are public methods + def new + end + + # These methods are responsible for producing output + def edit + end + +# Helper methods are private and can not be used as actions +private + + def foo + end + +end +---------------------------------------------- + +Private methods in a controller are also used as filters, which will be covered later in this guide. + +As an example, if the user goes to `/clients/new` in your application to add a new client, a ClientsController instance will be created and the `new` method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client: + +[source, ruby] +---------------------------------------------- +def new + @client = Client.new +end +---------------------------------------------- + +The Layouts & rendering guide explains this in more detail. diff --git a/railties/doc/guides/actioncontroller/parameter_filtering.txt b/railties/doc/guides/actioncontroller/parameter_filtering.txt new file mode 100644 index 0000000000..e71afac662 --- /dev/null +++ b/railties/doc/guides/actioncontroller/parameter_filtering.txt @@ -0,0 +1,14 @@ +== Parameter filtering == + +Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The "filter_parameter_logging":http://api.rubyonrails.org/classes/ActionController/Base.html#M000837 can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" before they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": + +[code, ruby] +------------------------- +class ApplicationController < ActionController::Base + + filter_parameter_logging :password + +end +------------------------- + +The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true. diff --git a/railties/doc/guides/actioncontroller/params.txt b/railties/doc/guides/actioncontroller/params.txt new file mode 100644 index 0000000000..c7a61d3cc0 --- /dev/null +++ b/railties/doc/guides/actioncontroller/params.txt @@ -0,0 +1,62 @@ +== Parameters == + +You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller: + +[code, ruby] +------------------------------------- +class ClientsController < ActionController::Base + + # This action uses query string parameters because it gets run by a HTTP GET request, + # but this does not make any difference to the way in which the parameters are accessed. + # The URL for this action would look like this in order to list activated clients: /clients/?status=activated + def index + if params[:status] = "activated" + @clients = Client.activated + else + @clients = Client.unativated + end + end + + # This action uses POST parameters. They are most likely coming from an HTML + # form which the user has submitted. The URL for this RESTful request will + # be "/clients", and the data will be sent as part of the request body. + def create + @client = Client.new(params[:client]) + if @client.save + redirect_to @client + else + # This line overrides the default rendering behavior, which would have been + # to render the "create" view. + render :action => "new" + end + end + +end +------------------------------------- + +=== Hash and array parameters === + +The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name: + +------------------------------------- +GET /clients?ids[]=1&ids[2]&ids[]=3 +------------------------------------- + +The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type. + +To send a hash you include the key name inside the brackets: + +------------------------------------- +
+ + + + +
+------------------------------------- + +The value of `params[:client]` when this form is submitted will be `{:name => "Acme", :phone => "12345", :address => {:postcode => "12345", :city => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`. + +=== Routing parameters === + +The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. diff --git a/railties/doc/guides/actioncontroller/request_response_objects.txt b/railties/doc/guides/actioncontroller/request_response_objects.txt new file mode 100644 index 0000000000..d335523a25 --- /dev/null +++ b/railties/doc/guides/actioncontroller/request_response_objects.txt @@ -0,0 +1,35 @@ +== The request and response objects == + +In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of "AbstractRequest":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html and the `response` method contains the "response object":http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb representing what is going to be sent back to the client. + +=== The request === + +The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "Rails API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html + + * host - The hostname used for this request. + * domain - The hostname without the first part (usually "www"). + * format - The content type requested by the client. + * method - The HTTP method used for the request. + * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head. + * headers - Returns a hash containing the headers associated with the request. + * port - The port number (integer) used for the request. + * protocol - The protocol used for the request. + * query_string - The query string part of the URL - everything after "?". + * remote_ip - The IP address of the client. + * url - The entire URL used for the request. + +==== path_parameters, query_parameters and request_parameters ==== + +TODO: Does this belong here? + +Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action. + +=== The response === + +The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values. + + * body - This is the string of data being sent back to the client. This is most often HTML. + * status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found. + * location - The URL the client is being redirected to, if any. + * content_type - The content type of the response. + * charset - The character set being used for the response. Default is "utf8". diff --git a/railties/doc/guides/actioncontroller/rescue.txt b/railties/doc/guides/actioncontroller/rescue.txt new file mode 100644 index 0000000000..6ff7ea67d8 --- /dev/null +++ b/railties/doc/guides/actioncontroller/rescue.txt @@ -0,0 +1,3 @@ +== Rescue == + +Describe how to use rescue_from et al to rescue exceptions in controllers. diff --git a/railties/doc/guides/actioncontroller/session.txt b/railties/doc/guides/actioncontroller/session.txt new file mode 100644 index 0000000000..b718770e63 --- /dev/null +++ b/railties/doc/guides/actioncontroller/session.txt @@ -0,0 +1,130 @@ +== Session == + +Your application sets up a session for each user which can persist small amounts of data between requests. The session is only available in the controller. It can be stored in a number of different session stores: + +TODO: Not sure if all of these are available by default. + + * CookieStore - Stores everything on the client. + * SQLSessionStore - Stores the data in a database using SQL. + * DRBStore - Stores the data on a DRb client. + * MemCacheStore - Stores the data in MemCache. + * ActiveRecordStore - Stores the data in a database using Active Record. + +All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server. + +The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store 4Kb of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application. + +If you need a different session storage mechanism, you can change it in the `config/environment.rb` file: + +[code, ruby] +------------------------------------------ +# Set to one of [:active_record_store, :sql_session_store, :drb_store, :mem_cache_store, :cookie_store] +config.action_controller.session_store = :active_record_store +------------------------------------------ + +=== Accessing the session === + +In your controller you can access the session through the `session` method. Session values are stored using key/value pairs like a hash: + +[code, ruby] +------------------------------------------ +class ApplicationController < ActionController::Base + +private + + # Finds the User with the ID stored in the session with the key :current_user_id + def current_user + @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id]) + end + +end +------------------------------------------ + +To store something in the session, just assign it to the key like a hash: + +[code, ruby] +------------------------------------------ +class LoginsController < ApplicationController + + # "Create" a login, aka "log the user in" + def create + if user = User.authenticate(params[:username, params[:password]) + # Save the user ID in the session so it can be used in subsequent requests + session[:current_user_id] = user.id + redirect_to root_url + end + end + +end +------------------------------------------ + +To remove something from the session, assign that key to be `nil`: + +[code, ruby] +------------------------------------------ +class LoginsController < ApplicationController + + # "Delete" a login, aka "log the user out" + def destroy + # Remove the user id from the session + session[:current_user_id] = nil + redirect_to root_url + end + +end +------------------------------------------ + +To reset the entire session, use `reset_session`. + +=== The flash === + +The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request: + +[code, ruby] +------------------------------------------ +class LoginsController < ApplicationController + + def destroy + session[:current_user_id] = nil + flash[:notice] = "You have successfully logged out" + redirect_to root_url + end + +end +------------------------------------------ + +The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout: + +[code, rhtml] +------------------------------------------ + + + <% if flash[:notice] -%> +

<%= flash[:notice] %>

+ <% end -%> + <% if flash[:error] -%> +

<%= flash[:error] %>

+ <% end -%> + + + +------------------------------------------ + +This way, if an action sets an error or a notice message, the layout will display it automatically. + +If you want a flash value to be carried over to another request, use the `keep` method: + +[code, ruby] +------------------------------------------ +class MainController < ApplicationController + + # Let's say this action corresponds to root_url, but you want all requests here to be redirected to + # UsersController#index. If an action sets the flash and redirects here, the values would normally be + # lost when another redirect happens, but you can use keep to make it persist for another request. + def index + flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice) + redirect_to users_url + end + +end +------------------------------------------ diff --git a/railties/doc/guides/actioncontroller/streaming.txt b/railties/doc/guides/actioncontroller/streaming.txt new file mode 100644 index 0000000000..b125f4b6c5 --- /dev/null +++ b/railties/doc/guides/actioncontroller/streaming.txt @@ -0,0 +1,91 @@ +== Streaming and file downloads == + +Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the "send_data":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624 and the "send_file":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623 methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you. + +To stream data to the client, use `send_data`: + +[code, ruby] +---------------------------- +require "prawn" +class ClientsController < ApplicationController + + # Generate a PDF document with information on the client and return it. + # The user will get the PDF as a file download. + def download_pdf + client = Client.find(params[:id]) + send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf") + end + +private + + def generate_pdf(client) + Prawn::Document.new do + text client.name, :align => :center + text "Address: #{client.address}" + text "Email: #{client.email}" + end.render + end + +end +---------------------------- + +The `download_pdf` action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The opposite and default value for this option is "attachment". + +=== Sending files === + +If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file. + +[code, ruby] +---------------------------- +class ClientsController < ApplicationController + + # Stream a file that has already been generated and stored on disk + def download_pdf + client = Client.find(params[:id]) + send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", :filename => "#{client.name}.pdf", :type => "application/pdf") + end + +end +---------------------------- + +NOTE: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to. + +NOTE: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. + +This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option. + +=== RESTful downloads === + +While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is a bit ugly. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action: + +[code, ruby] +---------------------------- +class ClientsController < ApplicationController + + # The user can request to receive this resource as HTML or PDF. + def show + @client = Client.find(params[:id]) + + respond_to do |format| + format.html + format.pdf{ render :pdf => generate_pdf(@client) } + end + end + +end +---------------------------- + +In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`: + +[code, ruby] +---------------------------- +Mime::Type.register "application/pdf", :pdf +---------------------------- + +NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect. + +Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL: + +---------------------------- +GET /clients/1.pdf +---------------------------- diff --git a/railties/doc/guides/actioncontroller/verification.txt b/railties/doc/guides/actioncontroller/verification.txt new file mode 100644 index 0000000000..129ff7e7b0 --- /dev/null +++ b/railties/doc/guides/actioncontroller/verification.txt @@ -0,0 +1,3 @@ +== Verification == + +Describe how to use the verify methods to make sure some prerequisites are met before an action gets run -- cgit v1.2.3 From 2ac20239c7f75419c39c2f40423f96cf9d9013b5 Mon Sep 17 00:00:00 2001 From: Tore Darell Date: Sat, 27 Sep 2008 00:24:40 +0200 Subject: Change code -> source in code blocks --- railties/doc/guides/actioncontroller/cookies.txt | 2 +- railties/doc/guides/actioncontroller/filters.txt | 12 ++++++------ railties/doc/guides/actioncontroller/http_auth.txt | 2 +- railties/doc/guides/actioncontroller/parameter_filtering.txt | 2 +- railties/doc/guides/actioncontroller/params.txt | 2 +- railties/doc/guides/actioncontroller/streaming.txt | 8 ++++---- 6 files changed, 14 insertions(+), 14 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/actioncontroller/cookies.txt b/railties/doc/guides/actioncontroller/cookies.txt index dbcec23e45..a845e452b2 100644 --- a/railties/doc/guides/actioncontroller/cookies.txt +++ b/railties/doc/guides/actioncontroller/cookies.txt @@ -4,7 +4,7 @@ Your application can store small amounts of data on the client - called cookies TODO: Find a real-world example where cookies are used -[code, ruby] +[source, ruby] ----------------------------------------- class FooController < ApplicationController diff --git a/railties/doc/guides/actioncontroller/filters.txt b/railties/doc/guides/actioncontroller/filters.txt index 96078ea208..2baf92d6ef 100644 --- a/railties/doc/guides/actioncontroller/filters.txt +++ b/railties/doc/guides/actioncontroller/filters.txt @@ -2,7 +2,7 @@ Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first: -[code, ruby] +[source, ruby] --------------------------------- class ApplicationController < ActionController::Base @@ -29,7 +29,7 @@ end The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the "before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704 method: -[code, ruby] +[source, ruby] --------------------------------- class ApplicationController < ActionController::Base @@ -40,7 +40,7 @@ end In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use "skip_before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711 : -[code, ruby] +[source, ruby] --------------------------------- class LoginsController < Application @@ -57,7 +57,7 @@ In addition to the before filters, you can run filters after an action has run o TODO: Find a real example for an around filter -[code, ruby] +[source, ruby] --------------------------------- class ApplicationController < Application @@ -80,7 +80,7 @@ While the most common way to use filters is by creating private methods and usin The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block: -[code, ruby] +[source, ruby] --------------------------------- class ApplicationController < ActionController::Base @@ -93,7 +93,7 @@ Note that the filter in this case uses `send` because the `logged_in?` method is The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class: -[code, ruby] +[source, ruby] --------------------------------- class ApplicationController < ActionController::Base diff --git a/railties/doc/guides/actioncontroller/http_auth.txt b/railties/doc/guides/actioncontroller/http_auth.txt index e3361609a9..5a95de0bb3 100644 --- a/railties/doc/guides/actioncontroller/http_auth.txt +++ b/railties/doc/guides/actioncontroller/http_auth.txt @@ -2,7 +2,7 @@ Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, "authenticate_or_request_with_http_basic":http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610 -[code, ruby] +[source, ruby] ------------------------------------- class AdminController < ApplicationController diff --git a/railties/doc/guides/actioncontroller/parameter_filtering.txt b/railties/doc/guides/actioncontroller/parameter_filtering.txt index e71afac662..dce4b252c3 100644 --- a/railties/doc/guides/actioncontroller/parameter_filtering.txt +++ b/railties/doc/guides/actioncontroller/parameter_filtering.txt @@ -2,7 +2,7 @@ Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The "filter_parameter_logging":http://api.rubyonrails.org/classes/ActionController/Base.html#M000837 can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" before they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": -[code, ruby] +[source, ruby] ------------------------- class ApplicationController < ActionController::Base diff --git a/railties/doc/guides/actioncontroller/params.txt b/railties/doc/guides/actioncontroller/params.txt index c7a61d3cc0..67f97b6135 100644 --- a/railties/doc/guides/actioncontroller/params.txt +++ b/railties/doc/guides/actioncontroller/params.txt @@ -2,7 +2,7 @@ You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller: -[code, ruby] +[source, ruby] ------------------------------------- class ClientsController < ActionController::Base diff --git a/railties/doc/guides/actioncontroller/streaming.txt b/railties/doc/guides/actioncontroller/streaming.txt index b125f4b6c5..6026a8c51b 100644 --- a/railties/doc/guides/actioncontroller/streaming.txt +++ b/railties/doc/guides/actioncontroller/streaming.txt @@ -4,7 +4,7 @@ Sometimes you may want to send a file to the user instead of rendering an HTML p To stream data to the client, use `send_data`: -[code, ruby] +[source, ruby] ---------------------------- require "prawn" class ClientsController < ApplicationController @@ -35,7 +35,7 @@ The `download_pdf` action in the example above will call a private method which If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file. -[code, ruby] +[source, ruby] ---------------------------- class ClientsController < ApplicationController @@ -58,7 +58,7 @@ This will read and stream the file 4Kb at the time, avoiding loading the entire While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is a bit ugly. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action: -[code, ruby] +[source, ruby] ---------------------------- class ClientsController < ApplicationController @@ -77,7 +77,7 @@ end In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`: -[code, ruby] +[source, ruby] ---------------------------- Mime::Type.register "application/pdf", :pdf ---------------------------- -- cgit v1.2.3 From a7e529191de38fb39dd9350fb740898c581c8893 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 26 Sep 2008 23:53:27 +0100 Subject: Change some more code -> source in code blocks --- railties/doc/guides/actioncontroller/session.txt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/actioncontroller/session.txt b/railties/doc/guides/actioncontroller/session.txt index b718770e63..50ed76e3ae 100644 --- a/railties/doc/guides/actioncontroller/session.txt +++ b/railties/doc/guides/actioncontroller/session.txt @@ -16,7 +16,7 @@ The default and recommended store, the Cookie Store, does not store session data If you need a different session storage mechanism, you can change it in the `config/environment.rb` file: -[code, ruby] +[source, ruby] ------------------------------------------ # Set to one of [:active_record_store, :sql_session_store, :drb_store, :mem_cache_store, :cookie_store] config.action_controller.session_store = :active_record_store @@ -26,7 +26,7 @@ config.action_controller.session_store = :active_record_store In your controller you can access the session through the `session` method. Session values are stored using key/value pairs like a hash: -[code, ruby] +[source, ruby] ------------------------------------------ class ApplicationController < ActionController::Base @@ -42,7 +42,7 @@ end To store something in the session, just assign it to the key like a hash: -[code, ruby] +[source, ruby] ------------------------------------------ class LoginsController < ApplicationController @@ -60,7 +60,7 @@ end To remove something from the session, assign that key to be `nil`: -[code, ruby] +[source, ruby] ------------------------------------------ class LoginsController < ApplicationController @@ -80,7 +80,7 @@ To reset the entire session, use `reset_session`. The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request: -[code, ruby] +[source, ruby] ------------------------------------------ class LoginsController < ApplicationController @@ -95,7 +95,7 @@ end The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout: -[code, rhtml] +[source, ruby] ------------------------------------------ @@ -114,7 +114,7 @@ This way, if an action sets an error or a notice message, the layout will displa If you want a flash value to be carried over to another request, use the `keep` method: -[code, ruby] +[source, ruby] ------------------------------------------ class MainController < ApplicationController -- cgit v1.2.3 From cd75947aad081c6502e3cad486c68fbb6f539d2d Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 27 Sep 2008 00:07:36 +0100 Subject: Add stuff to index --- railties/doc/guides/benchmarking_and_profiling/rubyprof.txt | 2 +- railties/doc/guides/index.txt | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt b/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt index 2dd5f2a99a..fa01d413a1 100644 --- a/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt +++ b/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt @@ -8,7 +8,7 @@ One of the things that is important to us is how long it takes to render the hom In the terminal run -[source, bash] +[source, ruby] ---------------------------------------------------------------------------- [User profiling_tester]$ gcruby tests/performance/homepage.rb ---------------------------------------------------------------------------- diff --git a/railties/doc/guides/index.txt b/railties/doc/guides/index.txt index 78228ea4a0..52f029da09 100644 --- a/railties/doc/guides/index.txt +++ b/railties/doc/guides/index.txt @@ -41,6 +41,16 @@ of your code. link:http://rails.lighthouseapp.com/projects/16213/tickets/2[Lighthouse Ticket] *********************************************************** +.link:actioncontroller/actioncontroller.html[Basics of Action Controller] +*********************************************************** +link:http://rails.lighthouseapp.com/projects/16213/tickets/17[Lighthouse Ticket] +*********************************************************** + +.link:activerecord/finders.html[Active Record Finders] +*********************************************************** +link:http://rails.lighthouseapp.com/projects/16213/tickets/16[Lighthouse Ticket] +*********************************************************** + .link:activerecord/association_basics.html[Active Record Associations] *********************************************************** link:http://rails.lighthouseapp.com/projects/16213/tickets/11[Lighthouse Ticket] -- cgit v1.2.3 From 3eb0b00463d53de830ffce7f99997c753612cd11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 27 Sep 2008 01:13:57 +0200 Subject: I wish people would add .DS_Store to their global gitignores --- railties/doc/guides/.DS_Store | Bin 6148 -> 0 bytes .../guides/benchmarking_and_profiling/examples/.DS_Store | Bin 6148 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 railties/doc/guides/.DS_Store delete mode 100644 railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store (limited to 'railties/doc') diff --git a/railties/doc/guides/.DS_Store b/railties/doc/guides/.DS_Store deleted file mode 100644 index aa78fbf68c..0000000000 Binary files a/railties/doc/guides/.DS_Store and /dev/null differ diff --git a/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store b/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store deleted file mode 100644 index 5008ddfcf5..0000000000 Binary files a/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store and /dev/null differ -- cgit v1.2.3 From 204e0653bd1ba5efb92026a30a0666bfd9b910cd Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Fri, 26 Sep 2008 20:25:39 -0500 Subject: Finished section on :render --- .../guides/actionview/layouts_and_rendering.txt | 114 ++++++++++++++++++++- 1 file changed, 113 insertions(+), 1 deletion(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt index c21ab72ee9..e205030f4b 100644 --- a/railties/doc/guides/actionview/layouts_and_rendering.txt +++ b/railties/doc/guides/actionview/layouts_and_rendering.txt @@ -80,30 +80,142 @@ WARNING: Using +render+ with +:action+ is a frequent source of confusion for Rai ==== Using +render+ with +:template+ +What if you want to render a template from an entirely different controller from the one that contains the action code? You can do that with the +:template+ option to +render+, which accepts the full path (relative to +app/views+) of the template to render. For example, if you're running code in an +AdminProductsController+ that lives in +app/controllers/admin+, you can render the results of an action to a template in +app/views/products+ this way: + +[source, ruby] +------------------------------------------------------- +render :template => 'products/show' +------------------------------------------------------- + ==== Using +render+ with +:file+ +If you want to use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications), you can use the +:file+ option to +render+: + +[source, ruby] +------------------------------------------------------- +render :file => "/u/apps/warehouse_app/current/app/views/products/show" +------------------------------------------------------- + +The +:file+ option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content. + +NOTE: By default, if you use the +:file+ option, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option + ==== Using +render+ with +:inline+ +The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid: + +[source, ruby] +------------------------------------------------------- +render :inline => "<% products.each do |p| %>

<%= p.name %>

<% end %>" +------------------------------------------------------- + +WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead. + ==== Using +render+ with +:update+ +You can also render javascript-based page updates inline using the +:update+ option to +render+: + +[source, ruby] +------------------------------------------------------- +render :update do |page| + page.replace_html 'warning', "Invalid options supplied" +end +------------------------------------------------------- + +WARNING: Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. I recommend using a separate rjs template instead, no matter how small the update. + ==== Rendering Text +You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+: + +[source, ruby] +------------------------------------------------------- +render :text => "OK" +------------------------------------------------------- + +TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML. + +NOTE: By default, if you use the +:text+ option, the file is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option + ==== Rendering JSON +JSON is a javascript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser: + +[source, ruby] +------------------------------------------------------- +render :json => @product +------------------------------------------------------- + +TIP: You don't need to call +to_json+ on the object that you want to render. If you use the +:json+ option, +render+ will automatically call +to_json+ for you. + ==== Rendering XML +Rails also has built-in support for converting objects to XML and rendering that XML back to the caller: + +[source, ruby] +------------------------------------------------------- +render :xml => @product +------------------------------------------------------- + +TIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you. + ==== Options for +render+ +Calls to the +render+ method generally accept four options: + +* +:content_type+ +* +:layout+ +* +:status+ +* +:location+ + ===== The +:content_type+ Option +By default, Rails will serve the results of a rendering operation with the MIME content-type of +text/html+ (or +application/json+ if you use the +:json+ option, or +application/xml+ for the +:xml+ option.). There are times when you might like to change this, and you can do so by setting the +:content_type+ option: + +[source, ruby] +------------------------------------------------------- +render :file => filename, :content_type => 'application/rss' +------------------------------------------------------- + ===== The +:layout+ Option -include :layout => false +With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide. To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+. If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+. + +You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action: + +[source, ruby] +------------------------------------------------------- +render :layout => 'special_layout' +------------------------------------------------------- + +You can also tell Rails to render with no layout at all: + +[source, ruby] +------------------------------------------------------- +render :layout => false +------------------------------------------------------- ===== The +:status+ Option +Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this: + +[source, ruby] +------------------------------------------------------- +render :status => 500 +render :status => :forbidden +------------------------------------------------------- + +Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how it maps symbols to status codes in that file. + ===== The +:location+ Option +You can use the +:location+ option to set the HTTP +Location+ header: + +[source, ruby] +------------------------------------------------------- +render :xml => photo, :location => photo_url(photo) +------------------------------------------------------- + === Using +redirect_to+ ==== Getting a Different Redirect Status Code -- cgit v1.2.3 From df046298715b1927a832973c4c29955696fee02c Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Fri, 26 Sep 2008 20:35:10 -0500 Subject: Fix substitution of path_prefix for name_prefix, some rewording. --- railties/doc/guides/routing/routing_outside_in.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/routing/routing_outside_in.txt b/railties/doc/guides/routing/routing_outside_in.txt index fcd435ce66..c04319496e 100644 --- a/railties/doc/guides/routing/routing_outside_in.txt +++ b/railties/doc/guides/routing/routing_outside_in.txt @@ -537,8 +537,8 @@ It's possible to do some quite complex things by combining +:path_prefix+ and +: [source, ruby] ------------------------------------------------------- map.resources :photos, :path_prefix => 'admin', :controller => 'admin/photos' -map.resources :tags, :path_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags' -map.resources :ratings, :path_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings' +map.resources :tags, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags' +map.resources :ratings, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings' ------------------------------------------------------- The good news is that if you find yourself using this level of complexity, you can stop. Rails supports _namespaced resources_ to make placing resources in their own folder a snap. Here's the namespaced version of those same three routes: @@ -551,7 +551,7 @@ map.namespace(:admin) do |admin| end ------------------------------------------------------- -As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. +As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. Even though you're not specifying +path_prefix+ explicitly, the routing code will calculate the appropriate +path_prefix+ from the route nesting. === Adding More RESTful Actions -- cgit v1.2.3 From 65c30e453ec03f5436baec44e09f2652c2844748 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 27 Sep 2008 15:02:39 +0100 Subject: Mark AR Associations guide as complete --- railties/doc/guides/index.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/index.txt b/railties/doc/guides/index.txt index 52f029da09..7e1bf09a39 100644 --- a/railties/doc/guides/index.txt +++ b/railties/doc/guides/index.txt @@ -11,7 +11,12 @@ These guides are complete and the authors are listed link:authors.html[here]. .link:migrations/migrations.html[Rails Database Migrations] *********************************************************** -TODO: Insert some description here. +This guide covers how you can use Active Record migrations to alter your database in a structured and organised manner. +*********************************************************** + +.link:activerecord/association_basics.html[Active Record Associations] +*********************************************************** +This guide covers all the associations provided by Active Record. *********************************************************** .link:routing/routing_outside_in.html[Rails Routing from the Outside In] @@ -51,11 +56,6 @@ link:http://rails.lighthouseapp.com/projects/16213/tickets/17[Lighthouse Ticket] link:http://rails.lighthouseapp.com/projects/16213/tickets/16[Lighthouse Ticket] *********************************************************** -.link:activerecord/association_basics.html[Active Record Associations] -*********************************************************** -link:http://rails.lighthouseapp.com/projects/16213/tickets/11[Lighthouse Ticket] -*********************************************************** - .link:forms/form_helpers.html[Action View Form Helpers] *********************************************************** link:http://rails.lighthouseapp.com/projects/16213/tickets/1[Lighthouse Ticket] -- cgit v1.2.3 From 444fb3ec692788de9c69d4ed722479e55541a546 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sat, 27 Sep 2008 20:38:11 -0500 Subject: Finished rendering and redirecting section. --- .../guides/actionview/layouts_and_rendering.txt | 149 +++++++++++++++++++++ 1 file changed, 149 insertions(+) (limited to 'railties/doc') diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt index e205030f4b..20ced5913f 100644 --- a/railties/doc/guides/actionview/layouts_and_rendering.txt +++ b/railties/doc/guides/actionview/layouts_and_rendering.txt @@ -111,6 +111,13 @@ render :inline => "<% products.each do |p| %>

<%= p.name %>

<% end %>" WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead. +By default, inline rendering uses ERb. You can force it to use Builder instead with the +:type+ option: + +[source, ruby] +------------------------------------------------------- +render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder +------------------------------------------------------- + ==== Using +render+ with +:update+ You can also render javascript-based page updates inline using the +:update+ option to +render+: @@ -216,12 +223,113 @@ You can use the +:location+ option to set the HTTP +Location+ header: render :xml => photo, :location => photo_url(photo) ------------------------------------------------------- +==== Avoiding Double Render Errors + +Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that +render+ works. + +For example, here's some code that will trigger this error: + +[source, ruby] +------------------------------------------------------- +def show + @book = Book.find(params[:id]) + if @book.special? + render :action => "special_show" + end +end +------------------------------------------------------- + +If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +show+ view - and throw an error. The solution is simple: make sure that you only have one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method: + +[source, ruby] +------------------------------------------------------- +def show + @book = Book.find(params[:id]) + if @book.special? + render :action => "special_show" and return + end +end +------------------------------------------------------- + === Using +redirect_to+ +Another way to handle returning responses to a HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call: + +[source, ruby] +------------------------------------------------------- +redirect_to photos_path +------------------------------------------------------- + +You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from: + +------------------------------------------------------- +redirect_to :back +------------------------------------------------------- + ==== Getting a Different Redirect Status Code +Rails uses HTTP status code 302 (permanent redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the +:status+ option: + +------------------------------------------------------- +redirect_to photos_path, :status => 301 +------------------------------------------------------- + +Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations. + +==== The Difference Between +render+ and +redirect+ + +Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back a HTTP 302 status code. + +Consider these actions to see the difference: + +[source, ruby] +------------------------------------------------------- +def index + @books = Book.find(:all) +end + +def show + @book = Book.find(params[:id]) + if @book.nil? + render :action => "index" and return + end +end +------------------------------------------------------- + +With the code in this form, there will be likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering: + +[source, ruby] +------------------------------------------------------- +def index + @books = Book.find(:all) +end + +def show + @book = Book.find(params[:id]) + if @book.nil? + redirect_to :action => "index" and return + end +end +------------------------------------------------------- + +With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well. + === Using +head+ To Build Header-Only Responses +The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header: + +[source, ruby] +------------------------------------------------------- +head :bad_request +------------------------------------------------------- + +Or you can use other HTTP headers to convey additional information: + +[source, ruby] +------------------------------------------------------- +head :created, :location => photo_path(@photo) +------------------------------------------------------- + == Structuring Layouts === Include Statements @@ -239,3 +347,44 @@ render :xml => photo, :location => photo_url(photo) http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket] * September 20, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- cgit v1.2.3 From fd9d92a14198f1774e99087b18c19b5b6a6872d9 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sun, 28 Sep 2008 08:34:46 -0500 Subject: Image updates & reorganization. First release version. --- .../doc/guides/activerecord/association_basics.txt | 387 +++++++++++++-------- .../activerecord/images/has_many_through.png | Bin 112630 -> 100220 bytes .../doc/guides/activerecord/images/polymorphic.png | Bin 0 -> 85248 bytes 3 files changed, 238 insertions(+), 149 deletions(-) create mode 100644 railties/doc/guides/activerecord/images/polymorphic.png (limited to 'railties/doc') diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt index d33c0ac3cf..00402d5eda 100644 --- a/railties/doc/guides/activerecord/association_basics.txt +++ b/railties/doc/guides/activerecord/association_basics.txt @@ -345,6 +345,8 @@ class CreatePictures < ActiveRecord::Migration end ------------------------------------------------------- +image:images/polymorphic.png[Polymorphic Association Diagram] + === Self Joins In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations: @@ -614,6 +616,24 @@ class Order < ActiveRecord::Base end ------------------------------------------------------- +The +belongs_to+ association supports these options: + +* +:accessible+ +* +:class_name+ +* +:conditions+ +* +:counter_cache+ +* +:dependent+ +* +:foreign_key+ +* +:include+ +* +:polymorphic+ +* +:readonly+ +* +:select+ +* +:validate+ + +===== +:accessible+ + +The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. + ===== +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way: @@ -636,29 +656,6 @@ class Order < ActiveRecord::Base 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: @@ -703,6 +700,25 @@ Counter cache columns are added to the containing model's list of read-only attr 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. +===== +:dependent+ + +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. + +WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database. + +===== +:foreign_key+ + +By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: + +[source, ruby] +------------------------------------------------------- +class Order < ActiveRecord::Base + belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id" +end +------------------------------------------------------- + +TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. + ===== +:include+ You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models: @@ -747,15 +763,16 @@ Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. -===== +:validate+ +===== +:select+ -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. +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. -===== +:accessible+ +===== +:validate+ -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. +If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved. ==== When are Objects Saved? + Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either. === The has_one Association @@ -843,7 +860,6 @@ The +create__\_association__+ method returns a new object of the associated type ==== 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] @@ -853,6 +869,32 @@ class Supplier < ActiveRecord::Base end ------------------------------------------------------- +The +has_one+ association supports these options: + +* +:accessible+ +* +:as+ +* +:class_name+ +* +:conditions+ +* +:dependent+ +* +:foreign_key+ +* +:include+ +* +:order+ +* +:primary_key+ +* +:readonly+ +* +:select+ +* +:source+ +* +:source_type+ +* +:through+ +* +:validate+ + +===== +:accessible+ + +The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. + +===== +:as+ + +Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide. + ===== +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is billing, you'd set things up this way: @@ -875,10 +917,6 @@ class Supplier < ActiveRecord::Base end ------------------------------------------------------- -===== +:order+ - -The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. - ===== +: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+. @@ -896,10 +934,6 @@ 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: @@ -934,17 +968,21 @@ class Representative < ActiveRecord::Base end ------------------------------------------------------- -===== +:as+ +===== +:order+ -Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide. +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. -===== +:select+ +===== +:primary_key+ -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. +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. -===== +:through+ +===== +:readonly+ -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. +If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. + +===== +:select+ + +The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns. ===== +:source+ @@ -954,18 +992,14 @@ The +:source+ option specifies the source association name for a +has_one :throu The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association. -===== +:readonly+ +===== +:through+ -If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. +The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide. ===== +:validate+ If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved. -===== +: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. @@ -1138,6 +1172,39 @@ class Customer < ActiveRecord::Base end ------------------------------------------------------- +The +has_many+ association supports these options: + +* +:accessible+ +* +:as+ +* +:class_name+ +* +:conditions+ +* +:counter_sql+ +* +:dependent+ +* +:extend+ +* +:finder_sql+ +* +:foreign_key+ +* +:group+ +* +:include+ +* +:limit+ +* +:offset+ +* +:order+ +* +:primary_key+ +* +:readonly+ +* +:select+ +* +:source+ +* +:source_type+ +* +:through+ +* +:uniq+ +* +:validate+ + +===== +:accessible+ + +The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. + +===== +:as+ + +Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide. + ===== +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is transactions, you'd set things up this way: @@ -1171,16 +1238,25 @@ 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+ +===== +:counter_sql+ -The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). +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. -[source, ruby] -------------------------------------------------------- -class Customer < ActiveRecord::Base - has_many :orders, :order => "date_confirmed DESC" -end -------------------------------------------------------- +NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. + +===== +:dependent+ + +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. + +NOTE: This option is ignored when you use the +:through+ option on the association. + +===== +:extend+ + +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide. + +===== +:finder_sql+ + +Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary. ===== +:foreign_key+ @@ -1195,29 +1271,16 @@ 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_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. - -NOTE: This option is ignored when you use the +:through+ option on the association. - -===== +: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. +===== +:group+ -===== +:extend+ +The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL. -The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide. +[source, ruby] +------------------------------------------------------- +class Customer < ActiveRecord::Base + has_many :line_items, :through => :orders, :group => "orders.id" +end +------------------------------------------------------- ===== +:include+ @@ -1253,31 +1316,39 @@ class LineItem < ActiveRecord::Base end ------------------------------------------------------- -===== +:group+ +===== +:limit+ -The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL. +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 :line_items, :through => :orders, :group => "orders.id" + has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100 end ------------------------------------------------------- -===== +:limit+ +===== +:offset+ -The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. + +===== +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100 + has_many :orders, :order => "date_confirmed DESC" end ------------------------------------------------------- -===== +:offset+ +===== +:primary_key+ -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. +By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option. + +===== +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. ===== +:select+ @@ -1285,14 +1356,6 @@ The +:select+ option lets you override the SQL +SELECT+ clause that is used to r 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. @@ -1301,22 +1364,18 @@ The +:source+ option specifies the source association name for a +has_many :thro The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association. -===== +:uniq+ +===== +:through+ -Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option. +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. -===== +:readonly+ +===== +:uniq+ -If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. +Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option. ===== +:validate+ If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved. -===== +: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. @@ -1498,24 +1557,32 @@ class Parts < ActiveRecord::Base 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: +The +has_and_belongs_to_many+ association supports these options: + +* +:accessible+ +* +:association_foreign_key+ +* +:class_name+ +* +:conditions+ +* +:counter_sql+ +* +:delete_sql+ +* +:extend+ +* +:finder_sql+ +* +:foreign_key+ +* +:group+ +* +:include+ +* +:insert_sql+ +* +:join_table+ +* +:limit+ +* +:offset+ +* +:order+ +* +:readonly+ +* +:select+ +* +:uniq+ +* +:validate+ -[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+ +===== +:accessible+ -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: +The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. ===== +:association_foreign_key+ @@ -1531,47 +1598,38 @@ class User < ActiveRecord::Base end ------------------------------------------------------- -===== +:conditions+ +===== +:class_name+ -The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). +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, :conditions => "factory = 'Seattle'" + has_and_belongs_to_many :assemblies, :class_name => :gadgets end ------------------------------------------------------- -You can also set conditions via a hash: +===== +: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' } + 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 +ORDER BY+ clause). - +You can also set conditions via a hash: [source, ruby] ------------------------------------------------------- class Parts < ActiveRecord::Base - has_and_belongs_to_many :assemblies, :order => "assembly_name ASC" + has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' } 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. +If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle". ===== +:counter_sql+ @@ -1583,17 +1641,25 @@ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter 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+ +===== +:finder_sql+ -You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. +Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary. + +===== +:foreign_key+ + +By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: + +[source, ruby] +------------------------------------------------------- +class User < ActiveRecord::Base + has_and_belongs_to_many :friends, :class_name => :users, + :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" +end +------------------------------------------------------- ===== +:group+ @@ -1606,6 +1672,18 @@ class Parts < ActiveRecord::Base end ------------------------------------------------------- +===== +:include+ + +You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. + +===== +:insert_sql+ + +Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself. + +===== +:join_table+ + +If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default. + ===== +:limit+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. @@ -1621,22 +1699,32 @@ end 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+ +===== +:order+ -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. +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). + +[source, ruby] +------------------------------------------------------- +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :order => "assembly_name ASC" +end +------------------------------------------------------- ===== +:readonly+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. -===== +:validate+ +===== +:select+ -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. +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. -===== +:accessible+ +===== +:uniq+ -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. +Specify the +:uniq => true+ option to remove duplicates from the collection. +===== +:validate+ + +If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved. ==== When are Objects Saved? @@ -1746,5 +1834,6 @@ Extensions can refer to the internals of the association proxy using these three http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket] -* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) +* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. * September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) +* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) diff --git a/railties/doc/guides/activerecord/images/has_many_through.png b/railties/doc/guides/activerecord/images/has_many_through.png index 9872201416..85d7599925 100644 Binary files a/railties/doc/guides/activerecord/images/has_many_through.png and b/railties/doc/guides/activerecord/images/has_many_through.png differ diff --git a/railties/doc/guides/activerecord/images/polymorphic.png b/railties/doc/guides/activerecord/images/polymorphic.png new file mode 100644 index 0000000000..ff2fd9f76d Binary files /dev/null and b/railties/doc/guides/activerecord/images/polymorphic.png differ -- cgit v1.2.3 From c492288d1660f016f4b2cd1ed299e31786886a9b Mon Sep 17 00:00:00 2001 From: athonlab Date: Sun, 28 Sep 2008 19:33:10 +0530 Subject: Syntax fixes plus some modification and additions in multiple sections of testing guide. --- .../testing_rails_applications.txt | 137 +++++++++++++++------ 1 file changed, 98 insertions(+), 39 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt index 254fd99357..11ff2e6a41 100644 --- a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt +++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt @@ -2,15 +2,18 @@ A Guide to Testing Rails Applications ===================================== This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to: + * Understand Rails testing terminologies * Write unit, functional and integration tests for your application * Read about other popular testing approaches and plugins Assumptions: + * You have spent more than 15 minutes in building your first application * The guide has been written for Rails 2.1 and above -== Why write tests for your Rails applications? +== Why write tests for your Rails applications? == + * Since Ruby code that you write in your Rails application is interpreted, you may only find that its broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code and catching syntactical and logic errors. * Rails tests can also simulate browser requests and thus you can test your applications response without having to test it through your browser. * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring. @@ -63,7 +66,7 @@ The 'unit' folder is meant to hold tests for your models, 'functional' folder is ==== What They Are ==== -Fixtures is a fancy word for 'sample data'. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. +Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. You'll find fixtures under your 'test/fixtures' directory. When you run `script/generate model` to create a new model, fixture stubs will be automatically created and placed in this directory. @@ -92,7 +95,7 @@ Each fixture is given a 'name' followed by an indented list of colon-separated k ==== Comma Seperated ==== -Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures directory', but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv'). +Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures' directory, but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv'). A CSV fixture looks like this: @@ -111,7 +114,7 @@ The first line is the header. It is a comma-separated list of fields. The rest o * don't use blank lines * nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course. -Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name''-''counter''. In the above example, you would have: +Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name-counter''. In the above example, you would have: -------------------------------------------------------------- celebrity-holiday-figures-1 @@ -497,7 +500,11 @@ You would get to see the usage of some of these assertions in the next chapter. == Functional tests for your Controllers == -In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view. Thus, you should test for things such as: +In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view. + +=== What to include in your Functional Tests === + +You should test for things such as: * was the web request successful? * were we redirected to the right page? @@ -569,7 +576,7 @@ For those of you familiar with HTTP protocol, you'll know that get is a type of * head * delete -All of request types are methods that you can use, however, you'll probably end up using the first two more ofter than the others. +All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others. === The 4 Hashes of the Apocolypse === @@ -577,27 +584,26 @@ After the request has been made by using one of the 5 methods (get, post, etc… They are (starring in alphabetical order): -assigns +`assigns`:: Any objects that are stored as instance variables in actions for use in views. -cookies +`cookies`:: Any objects cookies that are set. -flash +`flash`:: Any objects living in the flash. -session +`session`:: Any object living in session variables. - As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name… except assigns. Check it out: -flash["gordon"] flash[:gordon] -session["shmession"] session[:shmession] -cookies["are_good_for_u"] cookies[:are_good_for_u] + flash["gordon"] flash[:gordon] + session["shmession"] session[:shmession] + cookies["are_good_for_u"] cookies[:are_good_for_u] # Because you can't use assigns[:something] for historical reasons: -assigns["something"] assigns(:something) + assigns["something"] assigns(:something) === Instance variables available === @@ -618,14 +624,58 @@ Another example that uses flash, assert_redirected_to, assert_difference end -------------------------------------------------- -=== Testing Views using assert_select === -http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html#M000749 +=== Testing Views === + +Testing the response to your request by asserting the presence of key html elements and their content is a good practice. `assert_select` allows you to do all this by using a simple yet powerful syntax. + +[NOTE] +`assert_tag` is now deprecated in favor of `assert_select` + +`assert_select(selector, [equality], [message])`:: +Ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object. + +`assert_select(element, selector, [equality], [message])`:: +Ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of HTML::Node) and its descendants. + +For example, you could verify the contents on the title element in your response with: + +[source,ruby] +-------------------------------------------------- +assert_select 'title', "Welcome to Rails Testing Guide" +-------------------------------------------------- + +You can also use nested `assert_select` blocks. In this case the inner `assert_select` will run the assertion on each element selected by the outer `assert_select` block. + +[source,ruby] +-------------------------------------------------- +assert_select 'ul.navigation' do + assert_select 'li.menu_item' +end +-------------------------------------------------- + +`assert_select` is really powerful and I would recommend you to go through its http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation] for its advanced usage. ==== Additional view based assertions ==== - * assert_select_rjs - * assert_select_email - * assert_select_encoded +`assert_select_email`:: +Allows you to make assertions on the body of an e-mail. + +[source,ruby] +-------------------------------------------------- +assert_select_email do + assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.' +end +-------------------------------------------------- + +`assert_select_rjs`:: +Allows you to make assertions on RJS response. `assert_select_rjs` has variants which allow you to narrow down upon the updated element or event a particular operation on an element. + +`assert_select_encoded`:: +Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements. + +`css_select(selector)`:: +`css_select(element, selector)`:: +Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array. == Integration Testing == @@ -660,25 +710,30 @@ end * You will have to include fixtures explicitly unlike unit and functional tests in which all the fixtures are loaded by default (through test_helper) * Additional helpers: https?, https!, host!, follow_redirect!, post/get_via_redirect, open_session, reset - -== Guide TODO == - * What to test in unit tests - * Testing views (assert_select) - * Examples for integration test - * Updating Rake tasks - * Update sectino on testing file uploads - * Updating the section on testing mailers - -== Rake tasks related to testing - -rake db:test:* - -rake test -rake test:units -rake test:functionals -rake test:integration -rake test:plugin - +== Rake Tasks for Testing + +The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project. + +.Default Rake tasks +[grid="all"] +------------------------- +Tasks Description +------------------------- +`rake test` Runs all unit, functional and integration tests. You can also simply run `rake` as _test_ target is default. +`rake test:units` Runs all the unit tests from 'test/unit' +`rake test:functionals` Runs all the functional tests from 'test/functional' +`rake test:integration` Runs all the integration tests from 'test/integration' +`rake test:recent` Tests recent changes +`rake test:uncommitted` Runs all the tests which are uncommitted. Only supports Subversion +`rake test:plugins` Run all the plugin tests from vendor/plugins/*/**/test (or specify with `PLUGIN=_name_`) +`rake db:test:clone` Recreate the test database from the current environment's database schema +`rake db:test:clone_structure` Recreate the test databases from the development structure +`rake db:test:load` Recreate the test database from the current schema.rb +`rake db:test:prepare` Check for pending migrations and load the test schema +`rake db:test:purge` Empty the test database. +------------------------- + +TIP: You can see all these rake task and their descriptions by running `rake --tasks --describe` == Testing Your Mailers == @@ -877,3 +932,7 @@ class ActionMailer::Base end ---------------------------------------------------------------- +== Guide TODO == + * Describe _setup_ and _teardown_ + * Examples for integration test + * Updating the section on testing mailers -- cgit v1.2.3 From 39607fa159aee0d3b9feb11a4c184e6d98610af5 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sun, 28 Sep 2008 16:08:25 -0500 Subject: Back mentions of accessible out of Associations guide --- .../doc/guides/activerecord/association_basics.txt | 40 +++++++++++----------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt index 00402d5eda..b91052f91f 100644 --- a/railties/doc/guides/activerecord/association_basics.txt +++ b/railties/doc/guides/activerecord/association_basics.txt @@ -618,7 +618,7 @@ end The +belongs_to+ association supports these options: -* +:accessible+ +// * +:accessible+ * +:class_name+ * +:conditions+ * +:counter_cache+ @@ -630,10 +630,10 @@ The +belongs_to+ association supports these options: * +:select+ * +:validate+ -===== +:accessible+ - -The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. - +// ===== +:accessible+ +// +// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association. +// ===== +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way: @@ -871,7 +871,7 @@ end The +has_one+ association supports these options: -* +:accessible+ +// * +:accessible+ * +:as+ * +:class_name+ * +:conditions+ @@ -887,10 +887,10 @@ The +has_one+ association supports these options: * +:through+ * +:validate+ -===== +:accessible+ - -The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. - +// ===== +:accessible+ +// +// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association. +// ===== +:as+ Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide. @@ -1174,7 +1174,7 @@ end The +has_many+ association supports these options: -* +:accessible+ +// * +:accessible+ * +:as+ * +:class_name+ * +:conditions+ @@ -1197,10 +1197,10 @@ The +has_many+ association supports these options: * +:uniq+ * +:validate+ -===== +:accessible+ - -The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. - +// ===== +:accessible+ +// +// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association. +// ===== +:as+ Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide. @@ -1559,7 +1559,7 @@ end The +has_and_belongs_to_many+ association supports these options: -* +:accessible+ +// * +:accessible+ * +:association_foreign_key+ * +:class_name+ * +:conditions+ @@ -1580,10 +1580,10 @@ The +has_and_belongs_to_many+ association supports these options: * +:uniq+ * +:validate+ -===== +:accessible+ - -The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association. - +// ===== +:accessible+ +// +// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association. +// ===== +:association_foreign_key+ By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly: -- cgit v1.2.3 From a79942542eb022812ebd6cf2f857d8ad5f6e1f07 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sun, 28 Sep 2008 17:28:26 -0500 Subject: Layout & Rendering Guide --- .../guides/actionview/layouts_and_rendering.txt | 334 ++++++++++++++++++++- railties/doc/guides/index.txt | 10 + 2 files changed, 340 insertions(+), 4 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt index 20ced5913f..5a370500e5 100644 --- a/railties/doc/guides/actionview/layouts_and_rendering.txt +++ b/railties/doc/guides/actionview/layouts_and_rendering.txt @@ -1,5 +1,5 @@ Layouts and Rendering in Rails -===================================== +============================== This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to: @@ -332,21 +332,347 @@ head :created, :location => photo_path(@photo) == Structuring Layouts -=== Include Statements +When Rails renders a view as a response, it does so by combining the view with the current layout. To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+. If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+. You can also specify a particular layout by using the +:layout+ option to +render+. + +Within a layout, you have access to three tools for combining different bits of output to form the overall response: + +* Asset tags +* +yield+ and +content_for+ +* Partials + +I'll discuss each of these in turn. + +=== Asset Tags + +Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag: + +* auto_discovery_link_tag +* javascript_include_tag +* stylesheet_link_tag +* image_tag + +You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the ++ section of a layout. + +WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link. + +==== Linking to Feeds with +auto_discovery_link_tag+ + +The +auto_discovery_link_tag helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag: + +[source, ruby] +------------------------------------------------------- +<%= auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS Feed"}) %> +------------------------------------------------------- + +There are three tag options available for +auto_discovery_link_tag+: + +* +:rel+ specifies the +rel+ value in the link (defaults to "alternate") +* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically +* +:title+ specifies the title of the link + +==== Linking to Javascript Files with +javascript_include_tag+ + +The +javascript_include_tag+ helper returns an HTML +