Skip to content
Browse files

Merge docrails

  • Loading branch information...
1 parent 9605541 commit a17027d13a48e1e64b14a28e7d58e341812f8cb4 @lifo lifo committed Sep 13, 2008
View
28 actionpack/lib/action_controller/assertions/routing_assertions.rb
@@ -10,32 +10,32 @@ module RoutingAssertions
# and a :method containing the required HTTP verb.
#
# # assert that POSTing to /items will call the create action on ItemsController
- # assert_recognizes({:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post})
+ # assert_recognizes {:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post}
#
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
# extras argument, appending the query string on the path directly will not work. For example:
#
# # assert that a path of '/items/list/1?view=print' returns the correct options
- # assert_recognizes({:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" })
+ # assert_recognizes {:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" }
#
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
#
# ==== Examples
# # Check the default route (i.e., the index action)
- # assert_recognizes({:controller => 'items', :action => 'index'}, 'items')
+ # assert_recognizes {:controller => 'items', :action => 'index'}, 'items'
#
# # Test a specific action
- # assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list')
+ # assert_recognizes {:controller => 'items', :action => 'list'}, 'items/list'
#
# # Test an action with a parameter
- # assert_recognizes({:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1')
+ # assert_recognizes {:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1'
#
# # Test a custom route
- # assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1')
+ # assert_recognizes {:controller => 'items', :action => 'show', :id => '1'}, 'view/item1'
#
# # Check a Simply RESTful generated route
- # assert_recognizes(list_items_url, 'items/list')
+ # assert_recognizes list_items_url, 'items/list'
def assert_recognizes(expected_options, path, extras={}, message=nil)
if path.is_a? Hash
request_method = path[:method]
@@ -67,13 +67,13 @@ def assert_recognizes(expected_options, path, extras={}, message=nil)
#
# ==== Examples
# # Asserts that the default action is generated for a route with no action
- # assert_generates("/items", :controller => "items", :action => "index")
+ # assert_generates "/items", :controller => "items", :action => "index"
#
# # Tests that the list action is properly routed
- # assert_generates("/items/list", :controller => "items", :action => "list")
+ # assert_generates "/items/list", :controller => "items", :action => "list"
#
# # Tests the generation of a route with a parameter
- # assert_generates("/items/list/1", { :controller => "items", :action => "list", :id => "1" })
+ # assert_generates "/items/list/1", { :controller => "items", :action => "list", :id => "1" }
#
# # Asserts that the generated route gives us our custom route
# assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
@@ -104,19 +104,19 @@ def assert_generates(expected_path, options, defaults={}, extras = {}, message=n
#
# ==== Examples
# # Assert a basic route: a controller with the default action (index)
- # assert_routing('/home', :controller => 'home', :action => 'index')
+ # assert_routing '/home', :controller => 'home', :action => 'index'
#
# # Test a route generated with a specific controller, action, and parameter (id)
- # assert_routing('/entries/show/23', :controller => 'entries', :action => 'show', id => 23)
+ # assert_routing '/entries/show/23', :controller => 'entries', :action => 'show', id => 23
#
# # Assert a basic route (controller + default action), with an error message if it fails
- # assert_routing('/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly')
+ # assert_routing '/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly'
#
# # Tests a route, providing a defaults hash
# assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"}
#
# # Tests a route with a HTTP method
- # assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
+ # assert_routing { :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" }
def assert_routing(path, options, defaults={}, extras={}, message=nil)
assert_recognizes(options, path, extras, message)
View
2 actionpack/lib/action_view/helpers/scriptaculous_helper.rb
@@ -95,7 +95,7 @@ def visual_effect(name, element_id = false, js_options = {})
# * <tt>:containment</tt> - Takes an element or array of elements to treat as
# potential drop targets (defaults to the original target element).
#
- # * <tt>:only</tt> - A CSS class name or arry of class names used to filter
+ # * <tt>:only</tt> - A CSS class name or array of class names used to filter
# out child elements as candidates.
#
# * <tt>:scroll</tt> - Determines whether to scroll the list during drag
View
38 activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -252,6 +252,10 @@ def simplified_type(field_type)
class IndexDefinition < Struct.new(:table, :name, :unique, :columns) #:nodoc:
end
+ # Abstract representation of a column definition. Instances of this type
+ # are typically created by methods in TableDefinition, and added to the
+ # +columns+ attribute of said TableDefinition object, in order to be used
+ # for generating a number of table creation or table changing SQL statements.
class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
def sql_type
@@ -275,9 +279,29 @@ def add_column_options!(sql, options)
end
end
- # Represents a SQL table in an abstract way.
- # Columns are stored as a ColumnDefinition in the +columns+ attribute.
+ # Represents the schema of an SQL table in an abstract way. This class
+ # provides methods for manipulating the schema representation.
+ #
+ # Inside migration files, the +t+ object in +create_table+ and
+ # +change_table+ is actually of this type:
+ #
+ # class SomeMigration < ActiveRecord::Migration
+ # def self.up
+ # create_table :foo do |t|
+ # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
+ # end
+ # end
+ #
+ # def self.down
+ # ...
+ # end
+ # end
+ #
+ # The table definitions
+ # The Columns are stored as a ColumnDefinition in the +columns+ attribute.
class TableDefinition
+ # An array of ColumnDefinition objects, representing the column changes
+ # that have been defined.
attr_accessor :columns
def initialize(base)
@@ -321,6 +345,12 @@ def [](name)
# * <tt>:scale</tt> -
# Specifies the scale for a <tt>:decimal</tt> column.
#
+ # For clarity's sake: the precision is the number of significant digits,
+ # while the scale is the number of digits that can be stored following
+ # the decimal point. For example, the number 123.45 has a precision of 5
+ # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
+ # range from -999.99 to 999.99.
+ #
# Please be aware of different RDBMS implementations behavior with
# <tt>:decimal</tt> columns:
# * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
@@ -374,6 +404,10 @@ def [](name)
# td.column(:huge_integer, :decimal, :precision => 30)
# # => huge_integer DECIMAL(30)
#
+ # # Defines a column with a database-specific type.
+ # td.column(:foo, 'polygon')
+ # # => foo polygon
+ #
# == Short-hand examples
#
# Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
View
29 activerecord/lib/active_record/locale/en-US.yml
@@ -25,9 +25,30 @@ en-US:
even: "must be even"
# Append your own errors here or at the model/attributes scope.
+ # You can define own errors for models or model attributes.
+ # The values :model, :attribute and :value are always available for interpolation.
+ #
+ # For example,
+ # models:
+ # user:
+ # blank: "This is a custom blank message for {{model}}: {{attribute}}"
+ # attributes:
+ # login:
+ # blank: "This is a custom blank message for User login"
+ # Will define custom blank validation message for User model and
+ # custom blank validation message for login attribute of User model.
models:
- # Overrides default messages
-
- attributes:
- # Overrides model and default messages.
+
+ # Translate model names. Used in Model.human_name().
+ #models:
+ # For example,
+ # user: "Dude"
+ # will translate User model name to "Dude"
+
+ # Translate model attribute names. Used in Model.human_attribute_name(attribute).
+ #attributes:
+ # For example,
+ # user:
+ # login: "Handle"
+ # will translate User attribute "login" as "Handle"
View
97 activerecord/lib/active_record/validations.rb
@@ -259,6 +259,8 @@ def to_xml(options={})
end
+ # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
+ #
# Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
# +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
# that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
@@ -297,8 +299,6 @@ def to_xml(options={})
# person.save # => true (and person is now saved in the database)
#
# An Errors object is automatically created for every Active Record.
- #
- # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
module Validations
VALIDATIONS = %w( validate validate_on_create validate_on_update )
@@ -313,9 +313,50 @@ def self.included(base) # :nodoc:
base.define_callbacks *VALIDATIONS
end
- # All of the following validations are defined in the class scope of the model that you're interested in validating.
- # They offer a more declarative way of specifying when the model is valid and when it is not. It is recommended to use
- # these over the low-level calls to +validate+ and +validate_on_create+ when possible.
+ # Active Record classes can implement validations in several ways. The highest level, easiest to read,
+ # and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
+ # +validates_associated+) documented below. These are sufficient for most model validations.
+ #
+ # Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
+ # validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
+ # when the record is invalid.
+ #
+ # At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
+ # to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
+ # and chaining.
+ #
+ # The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
+ # as documented in ActiveRecord::Validations.
+ #
+ # == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
+ #
+ # Calls to these methods add a validation method or block to the class. Again, this approach is recommended
+ # only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
+ # insufficient to handle the required validation.
+ #
+ # This can be done with a symbol pointing to a method:
+ #
+ # class Comment < ActiveRecord::Base
+ # validate :must_be_friends
+ #
+ # def must_be_friends
+ # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
+ # Or with a block which is passed the current record to be validated:
+ #
+ # class Comment < ActiveRecord::Base
+ # validate do |comment|
+ # comment.must_be_friends
+ # end
+ #
+ # def must_be_friends
+ # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
+ # This usage applies to +validate_on_create+ and +validate_on_update+ as well.
module ClassMethods
DEFAULT_VALIDATION_OPTIONS = {
:on => :save,
@@ -329,34 +370,6 @@ module ClassMethods
:equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
:odd => 'odd?', :even => 'even?' }.freeze
- # Adds a validation method or block to the class. This is useful when
- # overriding the +validate+ instance method becomes too unwieldy and
- # you're looking for more descriptive declaration of your validations.
- #
- # This can be done with a symbol pointing to a method:
- #
- # class Comment < ActiveRecord::Base
- # validate :must_be_friends
- #
- # def must_be_friends
- # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
- # end
- # end
- #
- # Or with a block which is passed the current record to be validated:
- #
- # class Comment < ActiveRecord::Base
- # validate do |comment|
- # comment.must_be_friends
- # end
- #
- # def must_be_friends
- # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
- # end
- # end
- #
- # This usage applies to +validate_on_create+ and +validate_on_update+ as well.
-
# Validates each attribute against a block.
#
# class Person < ActiveRecord::Base
@@ -509,13 +522,13 @@ def validates_presence_of(*attr_names)
#
# class Person < ActiveRecord::Base
# validates_length_of :first_name, :maximum=>30
- # validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
+ # validates_length_of :last_name, :maximum=>30, :message=>"less than {{count}} if you don't mind"
# validates_length_of :fax, :in => 7..32, :allow_nil => true
# validates_length_of :phone, :in => 7..32, :allow_blank => true
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
- # validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least %d character"
- # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with %d characters... don't play me."
- # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
+ # validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least {{count}} character"
+ # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with {{count}} characters... don't play me."
+ # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least {{count}} words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
# end
#
# Configuration options:
@@ -526,9 +539,9 @@ def validates_presence_of(*attr_names)
# * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
- # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)").
- # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)").
- # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)").
+ # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is {{count}} characters)").
+ # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is {{count}} characters)").
+ # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be {{count}} characters)").
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
@@ -731,7 +744,7 @@ def validates_format_of(*attr_names)
# class Person < ActiveRecord::Base
# validates_inclusion_of :gender, :in => %w( m f ), :message => "woah! what are you then!??!!"
# validates_inclusion_of :age, :in => 0..99
- # validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %s is not included in the list"
+ # validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension {{value}} is not included in the list"
# end
#
# Configuration options:
@@ -765,7 +778,7 @@ def validates_inclusion_of(*attr_names)
# class Person < ActiveRecord::Base
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
- # validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %s is not allowed"
+ # validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension {{value}} is not allowed"
# end
#
# Configuration options:
View
12 activesupport/lib/active_support/core_ext/array/grouping.rb
@@ -7,16 +7,16 @@ module Grouping
# Splits or iterates over the array in groups of size +number+,
# padding any remaining slots with +fill_with+ unless it is +false+.
#
- # %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
+ # %w(1 2 3 4 5 6 7).in_groups_of(3) {|group| p group}
# ["1", "2", "3"]
# ["4", "5", "6"]
# ["7", nil, nil]
#
- # %w(1 2 3).in_groups_of(2, '&nbsp;') {|g| p g}
+ # %w(1 2 3).in_groups_of(2, '&nbsp;') {|group| p group}
# ["1", "2"]
# ["3", "&nbsp;"]
#
- # %w(1 2 3).in_groups_of(2, false) {|g| p g}
+ # %w(1 2 3).in_groups_of(2, false) {|group| p group}
# ["1", "2"]
# ["3"]
def in_groups_of(number, fill_with = nil)
@@ -42,17 +42,17 @@ def in_groups_of(number, fill_with = nil)
# Splits or iterates over the array in +number+ of groups, padding any
# remaining slots with +fill_with+ unless it is +false+.
#
- # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|g| p g}
+ # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
# ["1", "2", "3", "4"]
# ["5", "6", "7", nil]
# ["8", "9", "10", nil]
#
- # %w(1 2 3 4 5 6 7).in_groups(3, '&nbsp;') {|g| p g}
+ # %w(1 2 3 4 5 6 7).in_groups(3, '&nbsp;') {|group| p group}
# ["1", "2", "3"]
# ["4", "5", "&nbsp;"]
# ["6", "7", "&nbsp;"]
#
- # %w(1 2 3 4 5 6 7).in_groups(3, false) {|g| p g}
+ # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
# ["1", "2", "3"]
# ["4", "5"]
# ["6", "7"]
View
45 railties/Rakefile
@@ -272,20 +272,49 @@ Rake::RDocTask.new { |rdoc|
rdoc.rdoc_files.include('lib/commands/**/*.rb')
}
-guides = ['securing_rails_applications', 'testing_rails_applications', 'creating_plugins']
-guides_html_files = []
-guides.each do |guide_name|
- input = "doc/guides/#{guide_name}/#{guide_name}.txt"
- output = "doc/guides/#{guide_name}/#{guide_name}.html"
+# In this array, one defines the guides for which HTML output should be
+# generated. Specify the folder names of the guides. If the .txt filename
+# doesn't equal its folder name, then specify a hash: { 'folder_name' => 'basename' }
+guides = [
+ 'getting_started_with_rails',
+ 'securing_rails_applications',
+ 'testing_rails_applications',
+ 'creating_plugins',
+ 'migrations',
+ { 'routing' => 'routing_outside_in' },
+ { 'forms' =>'form_helpers' },
+ { 'activerecord' => 'association_basics' },
+ { 'debugging' => 'debugging_rails_applications' }
+]
+
+guides_html_files = [] # autogenerated from the 'guides' variable.
+guides.each do |entry|
+ if entry.is_a?(Hash)
+ guide_folder = entry.keys.first
+ guide_name = entry.values.first
+ else
+ guide_folder = entry
+ guide_name = entry
+ end
+ input = "doc/guides/#{guide_folder}/#{guide_name}.txt"
+ output = "doc/guides/#{guide_folder}/#{guide_name}.html"
guides_html_files << output
- file output => Dir["doc/guides/#{guide_name}/*.txt"] do
- sh "mizuho", input, "--template", "manualsonrails", "--multi-page",
- "--icons-dir", "../icons"
+ task output => Dir["doc/guides/#{guide_folder}/*.txt"] do
+ ENV['MANUALSONRAILS_INDEX_URL'] = '../index.html'
+ ENV.delete('MANUALSONRAILS_TOC')
+ sh "mizuho", input, "--template", "manualsonrails", "--icons-dir", "../icons"
end
end
+task 'doc/guides/index.html' => 'doc/guides/index.txt' do
+ ENV.delete('MANUALSONRAILS_INDEX_URL')
+ ENV['MANUALSONRAILS_TOC'] = 'no'
+ sh "mizuho", 'doc/guides/index.txt', "--template", "manualsonrails", "--icons-dir", "icons"
+end
+
desc "Generate HTML output for the guides"
task :generate_guides => guides_html_files
+task :generate_guides => 'doc/guides/index.html'
# Generate GEM ----------------------------------------------------------------------------
View
1,657 railties/doc/guides/activerecord/association_basics.txt
1,657 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
604 railties/doc/guides/debugging/debugging_rails_applications.txt
@@ -0,0 +1,604 @@
+Debugging Rails applications
+============================
+
+This guide covers how to debug Ruby on Rails applications. By referring to this guide, you will be able to:
+
+* Understand the purpose of debugging
+* Track down problems and issues in your application that your tests aren't identifying
+* Learn the different ways of debugging
+* Analyze the stack trace
+
+== View helpers for debugging
+
+=== debug
+
+`debug` will return a <pre>-tag that has object dumped by YAML. Generating readable output to inspect any object.
+
+[source, html]
+----------------------------------------------------------------------------
+<%= debug @post %>
+<p>
+ <b>Title:</b>
+ <%=h @post.title %>
+</p>
+----------------------------------------------------------------------------
+
+Will render something like this:
+
+----------------------------------------------------------------------------
+--- !ruby/object:Post
+attributes:
+ updated_at: 2008-09-05 22:55:47
+ body: It's a very helpful guide for debugging your Rails app.
+ title: Rails debugging guide
+ published: t
+ id: "1"
+ created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+
+Title: Rails debugging guide
+----------------------------------------------------------------------------
+
+
+=== do it yourself
+
+Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:
+
+[source, html]
+----------------------------------------------------------------------------
+<%= simple_format @post.to_yaml %>
+<p>
+ <b>Title:</b>
+ <%=h @post.title %>
+</p>
+----------------------------------------------------------------------------
+
+`to_yaml` converts the method to yaml format leaving it more readable and finally `simple_format` help us to render each line as in the console. This is how `debug` method does its magic.
+
+As a result of this, you will have something like this in your view:
+
+----------------------------------------------------------------------------
+--- !ruby/object:Post
+attributes:
+updated_at: 2008-09-05 22:55:47
+body: It's a very helpful guide for debugging your Rails app.
+title: Rails debugging guide
+published: t
+id: "1"
+created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+Title: Rails debugging guide
+----------------------------------------------------------------------------
+
+Another useful method for displaying object values is `inspect`, especially when working with arrays or hashes, it will print the object value as a string, for example:
+
+[source, html]
+----------------------------------------------------------------------------
+<%= [1, 2, 3, 4, 5].inspect %>
+<p>
+ <b>Title:</b>
+ <%=h @post.title %>
+</p>
+----------------------------------------------------------------------------
+
+Will be rendered as follows:
+
+----------------------------------------------------------------------------
+[1, 2, 3, 4, 5]
+
+Title: Rails debugging guide
+----------------------------------------------------------------------------
+
+== The logger
+
+=== What is it?
+
+Rails makes use of ruby’s standard `logger`, `Log4r`, or another logger that provides a similar interface can also be substituted if you wish.
+
+If you want to change the logger you can specify it in your `environment.rb` or any environment file.
+
+[source, ruby]
+----------------------------------------------------------------------------
+ActiveRecord::Base.logger = Logger.new(STDOUT)
+ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")
+----------------------------------------------------------------------------
+
+Or in the `__Initializer__` section, add _any_ of the following
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.logger = Logger.new(STDOUT)
+config.logger = Log4r::Logger.new("Application Log")
+----------------------------------------------------------------------------
+
+[TIP]
+By default, each log is created under `RAILS_ROOT/log/` and the log file name is `environment_name.log`.
+
+=== Log levels
+
+When something is logged it's printed into the corresponding log if the message log level is equal or higher than the configured log level. If you want to know the current log level just call `ActiveRecord::Base.logger.level` method.
+
+The available log levels are: +:debug+, +:info+, +:warn+, +:error+, +:fatal+, each level has a log level number from 0 up to 4 respectively. To change the default log level, use
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.log_level = Logger::WARN # In any environment initializer, or
+ActiveRecord::Base.logger.level = 0 # at any time
+----------------------------------------------------------------------------
+
+This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
+
+[TIP]
+Rails default log level is +info+ in production mode and +debug+ in development and test mode.
+
+=== Sending messages
+
+To write in the current log use the `logger.(debug|info|warn|error|fatal)` method from within a controller, model or mailer:
+
+[source, ruby]
+----------------------------------------------------------------------------
+logger.debug "Person attributes hash: #{@person.attributes.inspect}"
+logger.info "Processing the request..."
+logger.fatal "Terminating application, raised unrecoverable error!!!"
+----------------------------------------------------------------------------
+
+A common example:
+
+[source, ruby]
+----------------------------------------------------------------------------
+class PostsController < ApplicationController
+ # ...
+
+ def create
+ @post = Post.new(params[:post])
+ logger.debug "New post: #{@post.attributes.inspect}"
+ logger.debug "Post should be valid: #{@post.valid?}"
+
+ if @post.save
+ flash[:notice] = 'Post was successfully created.'
+ logger.debug "The post was saved and now is the user is going to be redirected..."
+ redirect_to(@post)
+ else
+ render :action => "new"
+ end
+ end
+
+ # ...
+end
+----------------------------------------------------------------------------
+
+Will be logged like this:
+
+----------------------------------------------------------------------------
+Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
+ Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!", "published"=>"0"}, "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!", "published"=>false, "created_at"=>nil}
+Post should be valid: true
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published", "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails', 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
+The post was saved and now is the user is going to be redirected...
+Redirected to #<Post:0x20af760>
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
+----------------------------------------------------------------------------
+
+Notice the logged lines, now you can search for any unexpected behavior in the output.
+
+By now you should know how to use the logs in any environment. Remember to take advantage of the log levels and use them wisely, mostly in production mode.
+
+== Debugging with ruby-debug
+
+Many times your code may not behave as you expect, sometimes you will try to print in logs, console or view values to make a diagnostic of the problem.
+
+Unfortunately, you won't find always the answer you are looking for this way. In that case, you will need to know what's happening and adventure into Rails, in this journey the debugger will be your best companion.
+
+If you ever wanted to learn about Rails source code but you didn't know where to start, this may be the best way, just debug any request to your application and use this guide to learn how to move in the code you have written but also go deeper into Rails code.
+
+=== Setup
+
+Ruby-debug comes as a gem so to install, just run:
+
+----------------------------------------------------------------------------
+$ sudo gem in ruby-debug
+----------------------------------------------------------------------------
+
+In case you want to download a particular version or get the source code, refer to link:http://rubyforge.org/projects/ruby-debug/[project's page on rubyforge].
+
+Rails has built-in support for ruby-debug since April 28, 2007. Inside any Rails application you can invoke the debugger by calling the `debugger` method.
+
+Let's take a look at an example:
+
+[source, ruby]
+----------------------------------------------------------------------------
+class PeopleController < ApplicationController
+ def new
+ debugger
+ @person = Person.new
+ end
+end
+----------------------------------------------------------------------------
+
+If you see the message in the console or logs:
+
+----------------------------------------------------------------------------
+***** Debugger requested, but was not available: Start server with --debugger to enable *****
+----------------------------------------------------------------------------
+
+Make sure you have started your web server with the option --debugger:
+
+----------------------------------------------------------------------------
+~/PathTo/rails_project$ script/server --debugger
+----------------------------------------------------------------------------
+
+[TIP]
+In development mode, you can dynamically `require \'ruby-debug\'` instead of restarting the server, in case it was started without `--debugger`.
+
+In order to use Rails debugging you'll need to be running either *WEBrick* or *Mongrel*. For the moment, no alternative servers are supported.
+
+=== The shell
+
+As soon as your application calls the `debugger` method, the debugger will be started in a debugger shell inside the terminal window you've fired up your application server and you will be placed in the ruby-debug's prompt `(rdb:n)`. The _n_ is the thread number.
+
+If you got there by a browser request, the browser will be hanging until the debugger has finished and the trace has completely run as any normal request.
+
+For example:
+
+----------------------------------------------------------------------------
+@posts = Post.find(:all)
+(rdb:7)
+----------------------------------------------------------------------------
+
+Now it's time to play and dig into our application. The first we are going to do is ask our debugger for help... so we type: `help` (You didn't see that coming, right?)
+
+----------------------------------------------------------------------------
+(rdb:7) help
+ruby-debug help v0.10.2
+Type 'help <command-name>' for help on a specific command
+
+Available commands:
+backtrace delete enable help next quit show trace
+break disable eval info p reload source undisplay
+catch display exit irb pp restart step up
+condition down finish list ps save thread var
+continue edit frame method putl set tmate where
+----------------------------------------------------------------------------
+
+[TIP]
+To view the help menu for any command use `help <command-name>` in active debug mode. For example: _help var_
+
+The second command before we move on, is one of the most useful command: `list` (or his shorthand `l`).
+
+This command will give us a starting point of where we are by printing 10 lines centered around the current line; the current line here is line 6 and is marked by =>.
+
+----------------------------------------------------------------------------
+(rdb:7) list
+[1, 10] in /PathToProject/posts_controller.rb
+ 1 class PostsController < ApplicationController
+ 2 # GET /posts
+ 3 # GET /posts.xml
+ 4 def index
+ 5 debugger
+=> 6 @posts = Post.find(:all)
+ 7
+ 8 respond_to do |format|
+ 9 format.html # index.html.erb
+ 10 format.xml { render :xml => @posts }
+----------------------------------------------------------------------------
+
+If we do it again, this time using just `l`, the next ten lines of the file will be printed out.
+
+----------------------------------------------------------------------------
+(rdb:7) l
+[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
+ 11 end
+ 12 end
+ 13
+ 14 # GET /posts/1
+ 15 # GET /posts/1.xml
+ 16 def show
+ 17 @post = Post.find(params[:id])
+ 18
+ 19 respond_to do |format|
+ 20 format.html # show.html.erb
+----------------------------------------------------------------------------
+
+And so on until the end of the current file, when the end of file is reached, it will start again from the beginning of the file and continue again up to the end, acting as a circular buffer.
+
+=== The context
+When we start debugging your application, we will be placed in different contexts as you go through the different parts of the stack.
+
+A context will be created when a stopping point or an event is reached. It has information about the suspended program which enable a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place the debugged program is stopped.
+
+At any time we can call the `backtrace` command (or alias `where`) to print the backtrace of the application, this is very helpful to know how we got where we are. If you ever wondered about how you got somewhere in your code, then `backtrace` is your answer.
+
+----------------------------------------------------------------------------
+(rdb:5) where
+ #0 PostsController.index
+ at line /PathTo/project/app/controllers/posts_controller.rb:6
+ #1 Kernel.send
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617
+...
+----------------------------------------------------------------------------
+
+You move anywhere you want in this trace using the `frame _n_` command, where _n_ is the specified frame number.
+
+----------------------------------------------------------------------------
+(rdb:5) frame 2
+#2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+----------------------------------------------------------------------------
+
+The available variables are the same as if we were running the code line by line, after all, that's what debugging is.
+
+Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) and `down [n]` commands in order to change the context _n_ frames up or down the stack respectively. _n_ defaults to one.
+
+=== Threads
+
+The debugger can list, stop, resume and switch between running threads, the command `thread` (or the abbreviated `th`) is used an allows the following options:
+
+* `thread` shows the current thread.
+* `thread list` command is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution.
+* `thread stop _n_` stop thread _n_.
+* `thread resume _n_` resume thread _n_.
+* `thread switch _n_` switch thread context to _n_.
+
+This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code.
+
+=== Inspecting variables
+
+Any expression can be evaluated in the current context, just type it!
+
+In the following example we will print the instance_variables defined within the current context.
+
+----------------------------------------------------------------------------
+@posts = Post.find(:all)
+(rdb:11) instance_variables
+["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
+----------------------------------------------------------------------------
+
+As you may have figured out, all variables that you can access from a controller are displayed, lets run the next line, we will use `next` (we will get later into this command).
+
+----------------------------------------------------------------------------
+(rdb:11) next
+Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
+ Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
+ Parameters: {"action"=>"index", "controller"=>"posts"}
+/PathToProject/posts_controller.rb:8
+respond_to do |format|
+-------------------------------------------------------------------------------
+
+And we'll ask again for the instance_variables.
+
+----------------------------------------------------------------------------
+(rdb:11) instance_variables.include? "@posts"
+true
+----------------------------------------------------------------------------
+
+Now +@posts+ is a included in them, because the line defining it was executed.
+
+[TIP]
+You can also step into *irb* mode with the command `irb` (of course!). This way an irb session will be started within the context you invoked it. But you must know that this is an experimental feature.
+
+To show variables and their values the `var` method is the most convenient way:
+
+----------------------------------------------------------------------------
+var
+(rdb:1) v[ar] const <object> show constants of object
+(rdb:1) v[ar] g[lobal] show global variables
+(rdb:1) v[ar] i[nstance] <object> show instance variables of object
+(rdb:1) v[ar] l[ocal] show local variables
+----------------------------------------------------------------------------
+
+This is a great way for inspecting the values of the current context variables. For example:
+
+----------------------------------------------------------------------------
+(rdb:9) var local
+ __dbg_verbose_save => false
+----------------------------------------------------------------------------
+
+You can also inspect for an object method this way:
+
+----------------------------------------------------------------------------
+(rdb:9) var instance Post.new
+@attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"...
+@attributes_cache = {}
+@new_record = true
+----------------------------------------------------------------------------
+
+[TIP]
+Commands `p` (print) and `pp` (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console.
+
+We can use also `display` to start watching variables, this is a good way of tracking values of a variable while the execution goes on.
+
+----------------------------------------------------------------------------
+(rdb:1) display @recent_comments
+1: @recent_comments =
+----------------------------------------------------------------------------
+
+The variables inside the displaying list will be printed with their values after we move in the stack. To stop displaying a variable use `undisplay _n_` where _n_ is the variable number (1 in the last example).
+
+=== Step by step
+
+Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution.
+
+Use `step` (abbreviated `s`) to continue running your program until the next logical stopping point and return control to ruby-debug.
+
+[TIP]
+You can also use `step+ _n_` and `step- _n_` to move forward or backward _n_ steps respectively.
+
+You may also use `next` which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move _n_ steps.
+
+The difference between `next` and `step` is that `step` stops at the next line of code executed, doing just single step, while `next` moves to the next line without descending inside methods.
+
+Lets run the next line in this example:
+
+[source, ruby]
+----------------------------------------------------------------------------
+class Author < ActiveRecord::Base
+ has_one :editorial
+ has_many :comments
+
+ def find_recent_comments(limit = 10)
+ debugger
+ @recent_comments ||= comments.find(
+ :all,
+ :conditions => ["created_at > ?", 1.week.ago],
+ :limit => limit
+ )
+ end
+end
+----------------------------------------------------------------------------
+
+[TIP]
+You can use ruby-debug while using script/console but remember to `require "ruby-debug"` before calling `debugger` method.
+
+----------------------------------------------------------------------------
+/PathTo/project $ script/console
+Loading development environment (Rails 2.1.0)
+>> require "ruby-debug"
+=> []
+>> author = Author.first
+=> #<Author id: 1, first_name: "Bob", last_name: "Smith", created_at: "2008-07-31 12:46:10", updated_at: "2008-07-31 12:46:10">
+>> author.find_recent_comments
+/PathTo/project/app/models/author.rb:11
+)
+----------------------------------------------------------------------------
+
+Now we are where we wanted to be, lets look around.
+
+----------------------------------------------------------------------------
+(rdb:1) list
+[6, 15] in /PathTo/project/app/models/author.rb
+ 6 debugger
+ 7 @recent_comments ||= comments.find(
+ 8 :all,
+ 9 :conditions => ["created_at > ?", 1.week.ago],
+ 10 :limit => limit
+=> 11 )
+ 12 end
+ 13 end
+----------------------------------------------------------------------------
+
+We are at the end of the line, but... was this line executed? We can inspect the instance variables.
+
+----------------------------------------------------------------------------
+(rdb:1) var instance
+@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
+@attributes_cache = {}
+----------------------------------------------------------------------------
+
++@recent_comments+ hasn't been defined yet, so we can assure this line hasn't been executed yet, lets move on this code.
+
+----------------------------------------------------------------------------
+(rdb:1) next
+/PathTo/project/app/models/author.rb:12
+@recent_comments
+(rdb:1) var instance
+@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
+@attributes_cache = {}
+@comments = []
+@recent_comments = []
+----------------------------------------------------------------------------
+
+Now we can see how +@comments+ relationship was loaded and @recent_comments defined because the line was executed.
+
+In case we want deeper in the stack trace we can move single `steps` and go into Rails code, this is the best way for finding bugs in your code, or maybe in Ruby or Rails.
+
+=== Breakpoints
+
+A breakpoint makes your application stop whenever a certain point in the program is reached and the debugger shell is invoked in that line.
+
+You can add breakpoints dynamically with the command `break` (or just `b`), there are 3 possible ways of adding breakpoints manually:
+
+* `break line`: set breakpoint in the _line_ in the current source file.
+* `break file:line [if expression]`: set breakpoint in the _line_ number inside the _file_. If an _expression_ is given it must evaluated to _true_ to fire up the debugger.
+* `break class(.|\#)method [if expression]`: set breakpoint in _method_ (. and \# for class and instance method respectively) defined in _class_. The _expression_ works the same way as with file:line.
+
+----------------------------------------------------------------------------
+(rdb:5) break 10
+Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10
+----------------------------------------------------------------------------
+
+Use `info breakpoints _n_` or `info break _n_` lo list breakpoints, is _n_ is defined it shows that breakpoints, otherwise all breakpoints are listed.
+
+----------------------------------------------------------------------------
+(rdb:5) info breakpoints
+Num Enb What
+ 1 y at filters.rb:10
+----------------------------------------------------------------------------
+
+Deleting breakpoints: use the command `delete _n_` to remove the breakpoint number _n_ or all of them if _n_ is not specified.
+
+----------------------------------------------------------------------------
+(rdb:5) delete 1
+(rdb:5) info breakpoints
+No breakpoints.
+----------------------------------------------------------------------------
+
+Enabling/Disabling breakpoints:
+
+* `enable breakpoints`: allow a list _breakpoints_ or all of them if none specified, to stop your program (this is the default state when you create a breakpoint).
+* `disable breakpoints`: the _breakpoints_ will have no effect on your program.
+
+=== Catching Exceptions
+
+The command `catch exception-name` (or just `cat exception-name`) can be used to intercept an exception of type _exception-name_ when there would otherwise be is no handler for it.
+
+To list existent catchpoints use `catch`.
+
+=== Resuming Execution
+
+* `continue` [line-specification] (or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
+* `finish` [frame-number] (or `fin`): execute until selected stack frame returns. If no frame number is given, we run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given we run until frame frames returns.
+
+=== Editing
+
+At any time, you may use any of this commands to edit the code you are evaluating:
+
+* `edit [file:line]`: edit _file_ using the editor specified by the EDITOR environment variable. A specific _line_ can also be given.
+* `tmate _n_` (abbreviated `tm`): open the current file in TextMate. It uses n-th frame if _n_ is specified.
+
+=== Quitting
+To exit the debugger, use the `quit` command (abbreviated `q`), or alias `exit`.
+
+A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again.
+
+=== Settings
+
+There are some settings that can be configured in ruby-debug to make it easier to debug your code, being among others useful options:
+
+* `set reload`: Reload source code when changed.
+* `set autolist`: Execute `list` command on every breakpoint.
+* `set listsize _n_`: Set number of source lines to list by default _n_.
+* `set forcestep`: Make sure `next` and `step` commands always move to a new line
+
+You can see the full list by using `help set` or `help set subcommand` to inspect any of them.
+
+[TIP]
+You can include any number of this configuration lines inside a `.rdebugrc` file in your HOME directory, and ruby-debug will read it every time it is loaded
+
+The following lines are recommended to be included in `.rdebugrc`:
+
+----------------------------------------------------------------------------
+set autolist
+set forcestep
+set listsize 25
+----------------------------------------------------------------------------
+
+
+== References
+
+* link:http://www.datanoise.com/ruby-debug[ruby-debug Homepage]
+* link:http://www.sitepoint.com/article/debug-rails-app-ruby-debug/[Article: Debugging a Rails application with ruby-debug]
+* link:http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/[ruby-debug Basics screencast]
+* link:http://railscasts.com/episodes/54-debugging-with-ruby-debug[Ryan Bate's ruby-debug screencast]
+* link:http://railscasts.com/episodes/24-the-stack-trace[Ryan Bate's stack trace screencast]
+* link:http://railscasts.com/episodes/56-the-logger[Ryan Bate's logger screencast]
+* link:http://bashdb.sourceforge.net/ruby-debug.html[Debugging with ruby-debug]
+* link:http://cheat.errtheblog.com/s/rdebug/[ruby-debug cheat sheet]
+* link:http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging[Ruby on Rails Wiki: How to Configure Logging]
View
270 railties/doc/guides/forms/form_helpers.txt
@@ -0,0 +1,270 @@
+Rails form helpers
+==================
+Mislav Marohnić <mislav.marohnic@gmail.com>
+
+Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
+
+In this guide we will:
+
+* Create search forms and similar kind of generic forms not representing any specific model in your application;
+* Make model-centric forms for creation and editing of specific database records;
+* Generate select boxes from multiple types of data;
+* Learn what makes a file upload form different;
+* Build complex, multi-model forms.
+
+NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit http://api.rubyonrails.org/[the Rails API documentation] for a complete reference.
+
+
+Basic forms
+-----------
+
+The most basic form helper is `form_tag`.
+
+----------------------------------------------------------------------------
+<% form_tag do %>
+ Form contents
+<% end %>
+----------------------------------------------------------------------------
+
+When called without arguments like this, it creates a form element that has the current page for action attribute and "POST" as method (some line breaks added for readability):
+
+.Sample rendering of `form_tag`
+----------------------------------------------------------------------------
+<form action="/home/index" method="post">
+ <div style="margin:0;padding:0">
+ <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
+ </div>
+ Form contents
+</form>
+----------------------------------------------------------------------------
+
+If you carefully observe this output, you can see that the helper generated something we didn't specify: a `div` element with a hidden input inside. This is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form which action isn't "GET" (provided that this security feature is enabled).
+
+NOTE: Throughout this guide, this `div` with the hidden input will be stripped away to have clearer code samples.
+
+Generic search form
+~~~~~~~~~~~~~~~~~~~
+
+Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of:
+
+1. a form element with "GET" method,
+2. a label for the input,
+3. a text input element, and
+4. a submit element.
+
+IMPORTANT: Always use "GET" as the method for search forms. Benefits are many: users are able to bookmark a specific search and get back to it; browsers cache results of "GET" requests, but not "POST"; and other.
+
+To create that, we will use `form_tag`, `label_tag`, `text_field_tag` and `submit_tag`, respectively.
+
+.A basic search form
+----------------------------------------------------------------------------
+<% form_tag(search_path, :method => "get") do %>
+ <%= label_tag(:q, "Search for:") %>
+ <%= text_field_tag(:q) %>
+ <%= submit_tag("Search") %>
+<% end %>
+----------------------------------------------------------------------------
+
+[TIP]
+============================================================================
+`search_path` can be a named route specified in "routes.rb":
+
+----------------------------------------------------------------------------
+map.search "search", :controller => "search"
+----------------------------------------------------------------------------
+============================================================================
+
+The above view code will result in the following markup:
+
+.Search form HTML
+----------------------------------------------------------------------------
+<form action="/search" method="get">
+ <label for="q">Search for:</label>
+ <input id="q" name="q" type="text" />
+ <input name="commit" type="submit" value="Search" />
+</form>
+----------------------------------------------------------------------------
+
+Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.
+
+TIP: For every form input, an ID attribute is generated from its name ("q" in our example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
+
+Multiple hashes in form helper attributes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+By now we've seen that the `form_tag` helper accepts 2 arguments: the path for the action attribute and an options hash for parameters (like `:method`).
+
+Identical to the `link_to` helper, the path argument doesn't have to be given as string or a named route. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. Still, we cannot simply write this:
+
+.A bad way to pass multiple hashes as method arguments
+----------------------------------------------------------------------------
+form_tag(:controller => "people", :action => "search", :method => "get")
+# => <form action="/people/search?method=get" method="post">
+----------------------------------------------------------------------------
+
+Here we wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL that we didn't want. The solution is to delimit the first hash (or both hashes) with curly brackets:
+
+.The correct way of passing multiple hashes as arguments
+----------------------------------------------------------------------------
+form_tag({:controller => "people", :action => "search"}, :method => "get")
+# => <form action="/people/search" method="get">
+----------------------------------------------------------------------------
+
+This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.
+
+WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly `expecting tASSOC` syntax error.
+
+Checkboxes, radio buttons and other controls
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Checkboxes are form controls that give the user a set of options they can enable or disable:
+
+----------------------------------------------------------------------------
+<%= check_box_tag(:pet_dog) %>
+ <%= label_tag(:pet_dog, "I own a dog") %>
+<%= check_box_tag(:pet_cat) %>
+ <%= label_tag(:pet_cat, "I own a cat") %>
+
+output:
+
+<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
+ <label for="pet_dog">I own a dog</label>
+<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
+ <label for="pet_cat">I own a cat</label>
+----------------------------------------------------------------------------
+
+Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (user can only pick one):
+
+----------------------------------------------------------------------------
+<%= radio_button_tag(:age, "child") %>
+ <%= label_tag(:age_child, "I am younger than 21") %>
+<%= radio_button_tag(:age, "adult") %>
+ <%= label_tag(:age_adult, "I'm over 21") %>
+
+output:
+
+<input id="age_child" name="age" type="radio" value="child" />
+ <label for="age_child">I am younger than 21</label>
+<input id="age_adult" name="age" type="radio" value="adult" />
+ <label for="age_adult">I'm over 21</label>
+----------------------------------------------------------------------------
+
+IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region.
+
+Other form controls we might mention are the text area, password input and hidden input:
+
+----------------------------------------------------------------------------
+<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
+<%= password_field_tag(:password) %>
+<%= hidden_field_tag(:parent_id, "5") %>
+
+output:
+
+<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
+<input id="password" name="password" type="password" />
+<input id="parent_id" name="parent_id" type="hidden" value="5" />
+----------------------------------------------------------------------------
+
+Hidden inputs are not shown to the user, but they hold data same as any textual input. Values inside them can be changed with JavaScript.
+
+TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating `filter_parameter_logging(:password)` in your ApplicationController.
+
+How do forms with PUT or DELETE methods work?
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?
+
+Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the _real_ method:
+
+----------------------------------------------------------------------------
+form_tag(search_path, :method => "put")
+
+output:
+
+<form action="/search" method="post">
+ <div style="margin:0;padding:0">
+ <input name="_method" type="hidden" value="put" />
+ <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
+ </div>
+ ...
+----------------------------------------------------------------------------
+
+When parsing POSTed data, Rails will take into account the special `"_method"` parameter and act as if the HTTP method was the one specified inside it ("PUT" in this example).
+
+
+Forms that deal with model attributes
+-------------------------------------
+
+When we're dealing with an actual model, we will use a different set of form helpers and have Rails take care of some details in the background. In the following examples we will handle an Article model. First, let us have the controller create one:
+
+.articles_controller.rb
+----------------------------------------------------------------------------
+def new
+ @article = Article.new
+end
+----------------------------------------------------------------------------
+
+Now we switch to the view. The first thing to remember is that we should use `form_for` helper instead of `form_tag`, and that we should pass the model name and object as arguments:
+
+.articles/new.html.erb
+----------------------------------------------------------------------------
+<% form_for :article, @article, :url => { :action => "create" } do |f| %>
+ <%= f.text_field :title %>
+ <%= f.text_area :body, :size => "60x12" %>
+ <%= submit_tag "Create" %>
+<% end %>
+----------------------------------------------------------------------------
+
+There are a few things to note here:
+
+1. `:article` is the name of the model and `@article` is our record.
+2. The URL for the action attribute is passed as a parameter named `:url`.
+3. The `form_for` method yields *a form builder* object (the `f` variable).
+4. Methods to create form controls are called *on* the form builder object `f` and *without* the `"_tag"` suffix (so `text_field_tag` becomes `f.text_field`).
+
+The resulting HTML is:
+
+----------------------------------------------------------------------------
+<form action="/articles/create" method="post">
+ <input id="article_title" name="article[title]" size="30" type="text" />
+ <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
+ <input name="commit" type="submit" value="Create" />
+</form>
+----------------------------------------------------------------------------
+
+A nice thing about `f.text_field` and other helper methods is that they will pre-fill the form control with the value read from the corresponding attribute in the model. For example, if we created the article instance by supplying an initial value for the title in the controller:
+
+----------------------------------------------------------------------------
+@article = Article.new(:title => "Rails makes forms easy")
+----------------------------------------------------------------------------
+
+... the corresponding input will be rendered with a value:
+
+----------------------------------------------------------------------------
+<input id="post_title" name="post[title]" size="30" type="text" value="Rails makes forms easy" />
+----------------------------------------------------------------------------
+
+Relying on record identification
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it *a resource*.
+
+When dealing with RESTful resources, our calls to `form_for` can get significantly easier if we rely on *record identification*. In short, we can just pass the model instance and have Rails figure out model name and the rest:
+
+----------------------------------------------------------------------------
+## Creating a new article
+# long-style:
+form_for(:article, @article, :url => articles_path)
+# same thing, short-style (record identification gets used):
+form_for(@article)
+
+## Editing an existing article
+# long-style:
+form_for(:article, @article, :url => article_path(@article), :method => "put")
+# short-style:
+form_for(@article)
+----------------------------------------------------------------------------
+
+Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`.
+
+WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly.
View
348 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.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
View
53 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.
+***********************************************************
View
85 railties/doc/guides/migrations/anatomy_of_a_migration.txt
@@ -0,0 +1,85 @@
+== Anatomy Of A Migration ==
+
+Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
+
+[source, ruby]
+------------------------
+class CreateProducts < ActiveRecord::Migration
+ def self.up
+ create_table :products do |t|
+ t.string :name
+ t.text :description
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :products
+ end
+end
+------------------------
+
+This migration adds a table called `products` with a string column called `name` and a text column called `description`. A primary key column called `id` will also be added, however since this is the default we do not need to ask for this. The timestamp columns `created_at` and `updated_at` which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table.
+
+Migrations are not limited to changing the schema. You can also use them to fix bad data in the database or populate new fields:
+
+[source, ruby]
+------------------------
+class AddReceiveNewsletterToUsers < ActiveRecord::Migration
+ def self.up
+ change_table :users do |t|
+ t.boolean :receive_newsletter, :default => false
+ end
+ User.update_all ["receive_newsletter = ?", true]
+ end
+
+ def self.down
+ remove_column :users, :receive_newsletter
+ end
+end
+------------------------
+
+This migration adds an `receive_newsletter` column to the `users` table. We want it to default to `false` for new users, but existing users are considered
+to have already opted in, so we use the User model to set the flag to `true` for existing users.
+
+NOTE: Some <<models,caveats>> apply to using models in your migrations.
+
+=== Migrations are classes
+A migration is a subclass of ActiveRecord::Migration that implements two class methods: +up+ (perform the required transformations) and +down+ (revert them).
+
+Active Record provides methods that perform common data definition tasks in a database independent way (you'll read about them in detail later):
+
+* `create_table`
+* `change_table`
+* `drop_table`
+* `add_column`
+* `remove_column`
+* `change_column`
+* `rename_column`
+* `add_index`
+* `remove_index`
+
+If you need to perform tasks specific to your database (for example create a <<foreign_key,foreign key>> constraint) then the `execute` function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could
+write code to set the value of that column for existing records (if necessary using your models).
+
+On databases that support transactions with statements that change the schema (such as PostgreSQL), migrations are wrapped in a transaction. If the database does not support this (for example MySQL and SQLite) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
+
+=== What's in a name ===
+
+Migrations are stored in files in `db/migrate`, one for each migration class. The name of the file is of the form `YYYYMMDDHHMMSS_create_products.rb`, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The migration class' name must match (the camelcased version of) the latter part of the file name. For example `20080906120000_create_products.rb` should define CreateProducts and `20080906120001_add_details_to_products.rb` should define AddDetailsToProducts. If you do feel the need to change the file name then you MUST update the name of the class inside or Rails will complain about a missing class.
+
+Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by setting `config.active_record.timestamped_migrations` to `false` in `environment.rb`.
+
+The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers.
+
+For example Alice adds migrations `20080906120000` and `20080906123000` and Bob adds `20080906124500` and runs it. Alice finishes her changes and checks in her migrations and Bob pulls down the latest changes. Rails knows that it has not run Alice's two migrations so `rake db:migrate` would run them (even though Bob's migration with a later timestamp has been run), and similarly migrating down would not run their down methods.
+
+Of course this is no substitution for communication within the team, for example if Alice's migration removed a table that Bob's migration assumed the existence of then trouble will still occur.
+
+=== Changing migrations ===
+
+Occasionally you will make a mistake while writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run `rake db:migrate`. You must rollback the migration (for example with `rake db:rollback`), edit your migration and then run `rake db:migrate` to run the corrected version.
+
+In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or more generally which has not been propagated beyond your development machine) is relatively harmless. Just use some common sense.
+
View
109 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.
+
View
7 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`).
View
21 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[]
View
111 railties/doc/guides/migrations/rakeing_around.txt
@@ -0,0 +1,111 @@
+== Running Migrations ==
+
+Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be `db:migrate`. In its most basic form it just runs the `up` method for all the migrations that have not yet been run. If there are no such migrations it exits.
+
+If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
+version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run
+
+------------------------------------
+rake db:migrate VERSION=20080906120000
+------------------------------------
+
+If this is greater than the current version (i.e. it is migrating upwards) this will run the `up` method on all migrations up to and including 20080906120000, if migrating downwards this will run the `down` method on all the migrations down to, but not including, 20080906120000.
+
+=== Rolling back ===
+
+A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run
+
+------------------
+rake db:rollback
+------------------
+
+This will run the `down` method from the latest migration. If you need to undo several migrations you can provide a `STEP` parameter:
+
+------------------
+rake db:rollback STEP=3
+------------------
+
+will run the `down` method fron the last 3 migrations.
+
+The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating back up again. As with the `db:rollback` task you can use the `STEP` parameter if you need to go more than one version back, for example
+
+------------------
+rake db:migrate:redo STEP=3
+------------------
+
+Neither of these Rake tasks do anything you could not do with `db:migrate`, they are simply more convenient since you do not need to explicitly specify the version to migrate to.
+
+Lastly, the `db:reset` task will drop the database, recreate it and load the current schema into it.
+
+NOTE: This is not the same as running all the migrations - see the section on <<schema,schema.rb>>.
+
+=== Being Specific ===
+
+If you need to run a specific migration up or down the `db:migrate:up` and `db:migrate:down` tasks will do that. Just specify the appropriate version and the corresponding migration will have its `up` or `down` method invoked, for example
+
+------------------
+rake db:migrate:up VERSION=20080906120000
+------------------
+
+will run the `up` method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example `db:migrate:up VERSION=20080906120000` will do nothing if Active Record believes that 20080906120000 has already been run.
+
+
+=== Being talkative ===
+
+By default migrations tell you exactly what they're doing and how long it took.
+A migration creating a table and adding an index might produce output like this
+-------------------------
+== 20080906170109 CreateProducts: migrating ===================================
+-- create_table(:products)
+ -> 0.0021s
+-- add_index(:products, :name)
+ -> 0.0026s
+== 20080906170109 CreateProducts: migrated (0.0059s) ==========================
+-------------------------
+Several methods are provided that allow you to control all this:
+
+* `suppress_messages` suppresses any output generated by its block
+* `say` outputs text (the second argument controls whether it is indented or not)
+* `say_with_time` outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.
+
+For example, this migration
+
+[source, ruby]
+----------------------
+class CreateProducts < ActiveRecord::Migration
+ def self.up
+ suppress_messages do
+ create_table :products do |t|
+ t.string :name
+ t.text :description
+ t.timestamps
+ end
+ end
+ say "Created a table"
+ suppress_messages {add_index :products, :name}
+ say "and an index!", true
+ say_with_time 'Waiting for a while' do
+ sleep 10
+ 250
+ end
+ end
+
+ def self.down
+ drop_table :products
+ end
+end
+----------------------
+
+generates the following output
+----------------------
+== 20080906170109 CreateProducts: migrating ===================================
+-- Created a table
+ -> and an index!
+-- Waiting for a while
+ -> 10.0001s
+ -> 250 rows
+== 20080906170109 CreateProducts: migrated (10.0097s) =========================
+----------------------
+
+If you just want Active Record to shut up then running `rake db:migrate VERBOSE=false` will suppress any output.
+
View
47 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.
+
View
46 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
+-------------------------
View
159 railties/doc/guides/migrations/writing_a_migration.txt
@@ -0,0 +1,159 @@
+== Writing a Migration ==
+
+Once you have created your migration using one of the generators it's time to get to work!
+
+=== Creating a table ===
+
+`create_table` will be one of your workhorses. A typical use would be
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.string :name
+end
+---------------------
+which creates a `products` table with a column called `name` (and as discussed below, an implicit `id` column).
+
+The object yielded to the block allows you create columns on the table. There are two ways of doing this. The first looks like
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.column :name, :string, :null => false
+end
+---------------------
+
+the second form, the so called "sexy" migrations, drops the somewhat redundant column method. Instead, the `string`, `integer` etc. methods create a column of that type. Subsequent parameters are identical.
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.string :name, :null => false
+end
+---------------------
+
+By default `create_table` will create a primary key called `id`. You can change the name of the primary key with the `:primary_key` option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass `:id => false`. If you need to pass database specific options you can place an sql fragment in the `:options` option. For example
+
+[source, ruby]
+---------------------
+create_table :products, :options => "ENGINE=InnoDB" do |t|
+ t.string :name, :null => false
+end
+---------------------
+Will append `ENGINE=InnoDB` to the sql used to create the table (this is Rails' default when using MySQL).
+
+The types Active Record supports are `:primary_key`, `:string`, `:text`, `:integer`, `:float`, `:decimal`, `:datetime`, `:timestamp`, `:time`, `:date`, `:binary`, `:boolean`.
+
+These will be mapped onto an appropriate underlying database type, for example with MySQL `:string` is mapped to `VARCHAR(255)`. You can create columns of
+types not supported by Active Record when using the non sexy syntax, for example
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.column :name, 'polygon', :null => false
+end
+---------------------
+This may however hinder portability to other databases.
+
+=== Changing tables ===
+
+`create_table`'s close cousin is `change_table`. Used for changing existing tables, it is used in a similar fashion to `create_table` but the object yielded to the block knows more tricks. For example
+
+[source, ruby]
+---------------------
+change_table :products do |t|
+ t.remove :description, :name
+ t.string :part_number
+ t.index :part_number
+ t.rename :upccode, :upc_code
+end
+---------------------
+removes the `description` column, creates a `part_number` column and adds an index on it. Finally it renames the `upccode` column. This is the same as doing
+
+[source, ruby]
+---------------------
+remove_column :products, :description
+remove_column :products, :name
+add_column :products, :part_number, :string
+add_index :products, :part_number
+rename_column :products, :upccode, :upc_code
+---------------------
+
+You don't have to keep repeating the table name and it groups all the statements related to modifying one particular table. The individual transformation names are also shorter, for example `remove_column` becomes just `remove` and `add_index` becomes just `index`.
+
+=== Special helpers ===
+
+Active Record provides some shortcuts for common functionality. It is for example very common to add both the `created_at` and `updated_at` columns and so there is a method that does exactly that:
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.timestamps
+end
+---------------------
+will create a new products table with those two columns whereas
+
+[source, ruby]
+---------------------
+change_table :products do |t|
+ t.timestamps
+end
+---------------------
+adds those columns to an existing table.
+
+The other helper is called `references` (also available as `belongs_to`). In its simplest form it just adds some readability
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.references :category
+end
+---------------------
+
+will create a `category_id` column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the `_id` for you. If you have polymorphic belongs_to associations then `references` will add both of the columns required:
+
+[source, ruby]
+---------------------
+create_table :products do |t|
+ t.references :attachment, :polymorphic => {:default => 'Photo'}
+end
+---------------------
+will add an `attachment_id` column and a string `attachment_type` column with a default value of 'Photo'.
+
+NOTE: The `references` helper does not actually create foreign key constraints for you. You will need to use `execute` for that or a plugin that adds <<foreign_key,foreign key support>>.
+
+If the helpers provided by Active Record aren't enough you can use the `execute` function to execute arbitrary SQL.
+
+For more details and examples of individual methods check the API documentation, in particular the documentation for http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html[ActiveRecord::ConnectionAdapters::SchemaStatements] (which provides the methods available in the `up` and `down` methods), http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html[ActiveRecord::ConnectionAdapters::TableDefinition] (which provides the methods available on the object yielded by `create_table`) and http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/Table.html[ActiveRecord::ConnectionAdapters::Table] (which provides the methods available on the object yielded by `change_table`).
+
+=== Writing your down method ===
+
+The `down` method of your migration should revert the transformations done by the `up` method. In other words the database should be unchanged if you do an `up` followed by a `down`. For example if you create a table in the up you should drop it in the `down` method. It is wise to do things in precisely the reverse order to in the `up` method. For example
+
+[source, ruby]
+---------------------
+class ExampleMigration < ActiveRecord::Migration
+
+ def self.up
+ create_table :products do |t|
+ t.references :category
+ end
+ #add a foreign key
+ execute "ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)"
+
+ add_column :users, :home_page_url, :string
+
+ rename_column :users, :email, :email_address
+ end
+
+ def self.down
+ rename_column :users, :email_address, :email
+ remove_column :users, :home_page_url
+ execute "ALTER TABLE products DROP FOREIGN KEY fk_products_categories"
+ drop_table :products
+ end
+end
+---------------------
+Sometimes your migration will do something which is just plain irreversible, for example it might destroy some data. In cases like those when you can't reverse the migration you can raise IrreversibleMigration from your `down` method. If someone tries to revert your migration an error message will be
+displayed saying that it can't be done.
+
View
838 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
+-------------------------------------------------------