h2. Ruby on Rails 3.2 Release Notes

Highlights in Rails 3.2:

* Faster Development Mode
* New Routing Engine
* Automatic Query Explains
* Tagged Logging

These release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/3-2-stable in the main Rails repository on GitHub.

endprologue.

h3. Upgrading to Rails 3.2

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.1 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.2. Then take heed of the following changes:

h4. Rails 3.2 requires at least Ruby 1.8.7

Rails 3.2 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.2 is also compatible with Ruby 1.9.2.

TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on 1.9.2 or 1.9.3 for smooth sailing.

h3. Creating a Rails 3.2 application

<shell>
# You should have the 'rails' rubygem installed
$ rails new myapp
$ cd myapp
</shell>

h4. Vendoring Gems

Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.

More information: - "Bundler homepage":http://gembundler.com

h4. Living on the Edge

+Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag:

<shell>
$ rails new myapp --edge
</shell>

If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag:

<shell>
$ ruby /path/to/rails/bin/rails new myapp --dev
</shell>

h3. Major Features

h4. Faster Development Mode & Routing

Rails 3.2 comes with a development mode that's noticeably faster. Inspired by "Active Reload":https://github.com/paneq/active_reload, Rails reloads classes only when files actually change. The performance gains are dramatic on a larger application. Route recognition also got a bunch faster thanks to the new "Journey":https://github.com/rails/journey engine.

h4. Automatic Query Explains

Rails 3.2 comes with a nice feature that explains queries generated by ARel by defining an +explain+ method in <tt>ActiveRecord::Relation</tt>. For example, you can run something like <tt>puts Person.active.limit(5).explain</tt> and the query ARel produces is explained. This allows to check for the proper indexes and further optimizations.

Queries that take more than half a second to run are *automatically* explained in the development mode. This threshold, of course, can be changed.

h4. Tagged Logging

When running a multi-user, multi-account application, it's a great help to be able to filter the log by who did what. TaggedLogging in Active Support helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging of such applications.

h3. Railties

* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting <tt>config.reload_classes_only_on_change</tt> to false.

* New applications get a flag <tt>config.active_record.auto_explain_threshold_in_seconds</tt> in the environments configuration files. With a value of <tt>0.5</tt> in <tt>development.rb</tt> and commented out in <tt>production.rb</tt>. No mention in <tt>test.rb</tt>.

* Added <tt>config.exceptions_app</tt> to set the exceptions application invoked by the +ShowException+ middleware when an exception happens. Defaults to <tt>ActionDispatch::PublicExceptions.new(Rails.public_path)</tt>.

* Added a <tt>DebugExceptions</tt> middleware which contains features extracted from <tt>ShowExceptions</tt> middleware.

* Display mounted engines' routes in <tt>rake routes</tt>.

* Allow to change the loading order of railties with <tt>config.railties_order</tt> like:

<ruby>
config.railties_order = [Blog::Engine, :main_app, :all]
</ruby>

* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box.

* Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications

* Default options to +rails new+ can be set in <tt>~/.railsrc</tt>.

* Add an alias +d+ for +destroy+. This works for engines too.

* Attributes on scaffold and model generators default to string. This allows the following: <tt>rails g scaffold Post title body:text author</tt>

* Allow scaffold/model/migration generators to accept "index" and "uniq" modifiers. For example,

<ruby>
rails g scaffold Post title:string:index author:uniq price:decimal{7,2}
</ruby>

will create indexes for +title+ and +author+ with the latter being an unique index. Some types such as decimal accept custom options. In the example, +price+ will be a decimal column with precision and scale set to 7 and 2 respectively.

* Remove old plugin generator +rails generate plugin+ in favor of +rails plugin new+ command.

* Remove old <tt>config.paths.app.controller</tt> API in favor of <tt>config.paths["app/controller"]</tt>.

h3. Action Pack

h4. Action Controller

* Make <tt>ActiveSupport::Benchmarkable</tt> a default module for <tt>ActionController::Base,</tt> so the <tt>#benchmark</tt> method is once again available in the controller context like it used to be.

* Added +:gzip+ option to +caches_page+. The default option can be configured globally using <tt>page_cache_compression</tt>.

* Rails will now use your default layout (such as "layouts/application") when you specify a layout with <tt>:only</tt> and <tt>:except</tt> condition, and those conditions fail.

<ruby>
class CarsController
  layout 'single_car', :only => :show
end
</ruby>

Rails will use 'layouts/single_car' when a request comes in :show action, and use 'layouts/application' (or 'layouts/cars', if exists) when a request comes in for any other actions.

* form_for is changed to use "#{action}_#{as}" as the css class and id if +:as+ option is provided. Earlier versions used "#{as}_#{action}".

* <tt>ActionController::ParamsWrapper</tt> on ActiveRecord models now only wrap <tt>attr_accessible</tt> attributes if they were set. If not, only the attributes returned by the class method +attribute_names+ will be wrapped. This fixes the wrapping of nested attributes by adding them to +attr_accessible+.

* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts.

* <tt>ActionDispatch::ShowExceptions</tt> is refactored. The controller is responsible for choosing to show exceptions. It's possible to override +show_detailed_exceptions?+ in controllers to specify which requests should provide debugging information on errors.

* Responders now return 204 No Content for API requests without a response body (as in the new scaffold).

* <tt>ActionController::TestCase</tt> cookies is refactored. Assigning cookies for test cases should now use <tt>cookies[]</tt>

<ruby>
cookies[:email] = 'user@example.com'
get :index
assert_equal 'user@example.com', cookies[:email]
</ruby>

To clear the cookies, use +clear+.

<ruby>
cookies.clear
get :index
assert_nil cookies[:email]
</ruby>

We now no longer write out HTTP_COOKIE and the cookie jar is persistent between requests so if you need to manipulate the environment for your test you need to do it before the cookie jar is created.

* <tt>send_file</tt> now guesses the MIME type from the file extension if +:type+ is not provided.

* MIME type entries for PDF, ZIP and other formats were added.

* Allow fresh_when/stale? to take a record instead of an options hash.

* Changed log level of warning for missing CSRF token from <tt>:debug</tt> to <tt>:warn</tt>.

* Assets should use the request protocol by default or default to relative if no request is available.

h5. Deprecations

* Deprecated implied layout lookup in controllers whose parent had a explicit layout set:

<ruby>
class ApplicationController
  layout "application"
end

class PostsController < ApplicationController
end
</ruby>

In the example above, Posts controller will no longer automatically look up for a posts layout. If you need this functionality you could either remove <tt>layout "application"</tt> from +ApplicationController+ or explicitly set it to +nil+ in +PostsController+.

h4. Action Dispatch

* Added <tt>ActionDispatch::RequestId</tt> middleware that'll make a unique X-Request-Id header available to the response and enables the <tt>ActionDispatch::Request#uuid</tt> method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog.

* The <tt>ShowExceptions</tt> middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in +env["action_dispatch.exception"]+ and with the <tt>PATH_INFO</tt> rewritten to the status code.

* Allow rescue responses to be configured through a railtie as in <tt>config.action_dispatch.rescue_responses</tt>.

h4. Action View

* Add +button_tag+ support to <tt>ActionView::Helpers::FormBuilder</tt>. This support mimics the default behavior of +submit_tag+.

<ruby>
<%= form_for @post do |f| %>
  <%= f.button %>
<% end %>
</ruby>

* Date helpers accept a new option <tt>:use_two_digit_numbers => true</tt>, that renders select boxes for months and days with a leading zero without changing the respective values. For example, this is useful for displaying ISO8601-style dates such as '2011-08-01'.

* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

<ruby>
<%= form_for(@offer, :namespace => 'namespace') do |f| %>
  <%= f.label :version, 'Version' %>:
  <%= f.text_field :version %>
<% end %>
</ruby>

* Limit the number of options for +select_year+ to 1000. Pass +:max_years_allowed+ option to set your own limit.

* +content_tag_for+ and +div_for+ can now take a collection of records. It will also yield the record as the first argument if you set a receiving argument in your block. So instead of having to do this:

<ruby>
@items.each do |item|
  content_tag_for(:li, item) do
     Title: <%= item.title %>
  end
end
</ruby>

You can do this:

<ruby>
content_tag_for(:li, @items) do |item|
  Title: <%= item.title %>
end
</ruby>

h5. Deprecations

* Passing formats or handlers to render :template and friends like <tt>render :template => "foo.html.erb"</tt> is deprecated. Instead, you can provide :handlers and :formats directly as an options: <tt> render :template => "foo", :formats => [:html, :js], :handlers => :erb</tt>.

h3. Active Record

* Implemented <tt>ActiveRecord::Relation#explain</tt>.

* Implements <tt>AR::Base.silence_auto_explain</tt> which allows the user to selectively disable automatic EXPLAINs within a block.

* Implements automatic EXPLAIN logging for slow queries. A new configuration parameter +config.active_record.auto_explain_threshold_in_seconds+ determines what's to be considered a slow query. Setting that to nil disables this feature. Defaults are 0.5 in development mode, and nil in test and production modes. As of this writing there's support for SQLite, MySQL (mysql2 adapter), and PostgreSQL.

* Added <tt>ActiveRecord::Base.store</tt> for declaring simple single-column key/value stores.

<ruby>
class User < ActiveRecord::Base
  store :settings, accessors: [ :color, :homepage ]
end

u = User.new(color: 'black', homepage: '37signals.com')
u.color                          # Accessor stored attribute
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
</ruby>

* Added ability to run migrations only for a given scope, which allows to run migrations only from one engine (for example to revert changes from an engine that need to be removed).

<ruby>
rake db:migrate SCOPE=blog
</ruby>

* Migrations copied from engines are now scoped with engine's name, for example <tt>01_create_posts.blog.rb</tt>.

* Implemented <tt>ActiveRecord::Relation#pluck</tt> method that returns an array of column values directly from the underlying table. This also works with serialized attributes.

<ruby>
Client.where(:active => true).pluck(:id)
# SELECT id from clients where active = 1
</ruby>

* Generated association methods are created within a separate module to allow overriding and composition. For a class named MyModel, the module is named <tt>MyModel::GeneratedFeatureMethods</tt>. It is included into the model class immediately after the +generated_attributes_methods+ module defined in Active Model, so association methods override attribute methods of the same name.

* Add <tt>ActiveRecord::Relation#uniq</tt> for generating unique queries.

<ruby>
Client.select('DISTINCT name')
</ruby>

..can be written as:

<ruby>
Client.select(:name).uniq
</ruby>

This also allows you to revert the uniqueness in a relation:

<ruby>
Client.select(:name).uniq.uniq(false)
</ruby>

* Support index sort order in SQLite, MySQL and PostgreSQL adapters.

* Allow the +:class_name+ option for associations to take a symbol in addition to a string. This is to avoid confusing newbies, and to be consistent with the fact that other options like :foreign_key already allow a symbol or a string.

<ruby>
has_many :clients, :class_name => :Client # Note that the symbol need to be capitalized
</ruby>

* In development mode, <tt>db:drop</tt> also drops the test database in order to be symmetric with <tt>db:create</tt>.

* Case-insensitive uniqueness validation avoids calling LOWER in MySQL when the column already uses a case-insensitive collation.

* Transactional fixtures enlist all active database connections. You can test models on different connections without disabling transactional fixtures.

* Add +first_or_create+, +first_or_create!+, +first_or_initialize+ methods to Active Record. This is a better approach over the old +find_or_create_by+ dynamic methods because it's clearer which arguments are used to find the record and which are used to create it.

<ruby>
User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson")
</ruby>

h4. Deprecations

* Automatic closure of connections in threads is deprecated. For example the following code is deprecated:

<ruby>
Thread.new { Post.find(1) }.join
</ruby>

It should be changed to close the database connection at the end of the thread:

<ruby>
Thread.new {
  Post.find(1)
  Post.connection.close
}.join
</ruby>

Only people who spawn threads in their application code need to worry about this change.

* The +set_table_name+, +set_inheritance_column+, +set_sequence_name+, +set_primary_key+, +set_locking_column+ methods are deprecated. Use an assignment method instead. For example, instead of +set_table_name+, use <tt>self.table_name=</tt>.

<ruby>
class Project < ActiveRecord::Base
  self.table_name = "project"
end
</ruby>

Or define your own <tt>self.table_name</tt> method:

<ruby>
class Post < ActiveRecord::Base
  def self.table_name
    "special_" + super
  end
end

Post.table_name # => "special_posts"

</ruby>

h3. Active Model

* Add <tt>ActiveModel::Errors#added?</tt> to check if a specific error has been added.

* Add ability to define strict validations with <tt>strict => true</tt> that always raises exception when fails.

* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior.

h4. Deprecations

* Deprecated <tt>define_attr_method</tt> in <tt>ActiveModel::AttributeMethods</tt> because this only existed to support methods like +set_table_name+ in Active Record, which are themselves being deprecated.

* Deprecated <tt>Model.model_name.partial_path</tt> in favor of <tt>model.to_partial_path</tt>.

h3. Active Resource

* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like 301 Moved Permanently and 302 Found.

h3. Active Support

* Added <tt>ActiveSupport:TaggedLogging</tt> that can wrap any standard +Logger+ class to provide tagging capabilities.

<ruby>
Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))

Logger.tagged("BCX") { Logger.info "Stuff" }
# Logs "[BCX] Stuff"

Logger.tagged("BCX", "Jason") { Logger.info "Stuff" }
# Logs "[BCX] [Jason] Stuff"

Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } }
# Logs "[BCX] [Jason] Stuff"
</ruby>

* The +beginning_of_week+ method in +Date+, +Time+ and +DateTime+ accepts an optional argument representing the day in which the week is assumed to start.

* <tt>ActiveSupport::Notifications.subscribed</tt> provides subscriptions to events while a block runs.

* Defined new methods <tt>Module#qualified_const_defined?</tt>, <tt>Module#qualified_const_get</tt> and <tt>Module#qualified_const_set</tt> that are analogous to the corresponding methods in the standard API, but accept qualified constant names.

* Added +#deconstantize+ which complements +#demodulize+ in inflections. This removes the rightmost segment in a qualified constant name.

* Added <tt>safe_constantize</tt> that constantizes a string but returns +nil+ instead of raising an exception if the constant (or part of it) does not exist.

* <tt>ActiveSupport::OrderedHash</tt> is now marked as extractable when using <tt>Array#extract_options!</tt>.

* Added <tt>Array#prepend</tt> as an alias for <tt>Array#unshift</tt> and <tt>Array#append</tt> as an alias for <tt>Array#<<</tt>.

* The definition of a blank string for Ruby 1.9 has been extended to Unicode whitespace. Also, in Ruby 1.8 the ideographic space U+3000 is considered to be whitespace.

* The inflector understands acronyms.

* Added <tt>Time#all_day</tt>, <tt>Time#all_week</tt>, <tt>Time#all_quarter</tt> and <tt>Time#all_year</tt> as a way of generating ranges.

<ruby>
Event.where(:created_at => Time.now.all_week)
Event.where(:created_at => Time.now.all_day)
</ruby>

* Added <tt>instance_accessor: false</tt> as an option to <tt>Class#cattr_accessor</tt> and friends.

* <tt>ActiveSupport::OrderedHash</tt> now has different behavior for <tt>#each</tt> and <tt>#each_pair</tt> when given a block accepting its parameters with a splat.

* Added <tt>ActiveSupport::Cache::NullStore</tt> for use in development and testing.

* Removed <tt>ActiveSupport::SecureRandom</tt> in favor of <tt>SecureRandom</tt> from the standard library.

h4. Deprecations

* Deprecated <tt>ActiveSupport::Memoizable</tt> in favor of Ruby memoization pattern.

* <tt>Module#synchronize</tt> is deprecated with no replacement. Please use monitor from ruby's standard library.

* Deprecated <tt>ActiveSupport::MessageEncryptor#encrypt</tt> and <tt>ActiveSupport::MessageEncryptor#decrypt</tt>.

*  <tt>ActiveSupport::BufferedLogger#silence</tt> is deprecated. If you want to squelch logs for a certain block, change the log level for that block.

* <tt>ActiveSupport::BufferedLogger#open_log</tt> is deprecated. This method should not have been public in the first place.

* <tt>ActiveSupport::BufferedLogger's</tt> behavior of automatically creating the directory for your log file is deprecated. Please make sure to create the directory for your log file before instantiating.

* <tt>ActiveSupport::BufferedLogger#auto_flushing</tt> is deprecated. Either set the sync level on the underlying file handle like this. Or tune your filesystem. The FS cache is now what controls flushing.

<ruby>
f = File.open('foo.log', 'w')
f.sync = true
ActiveSupport::BufferedLogger.new f
</ruby>

* <tt>ActiveSupport::BufferedLogger#flush</tt> is deprecated. Set sync on your filehandle, or tune your filesystem.

h3. Credits

See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

Rails 3.2 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev.
