-
The new rake task assets:clean removes precompiled assets. [fxn]
-
Application and plugin generation run bundle install unless
--skip-gemfile
or--skip-bundle
. [fxn] -
Fixed database tasks for jdbc* adapters #jruby [Rashmi Yadav]
-
Template generation for jdbcpostgresql #jruby [Vishnu Atrai]
-
Template generation for jdbcmysql and jdbcsqlite3 #jruby [Arun Agrawal]
-
The -j option of the application generator accepts an arbitrary string. If passed "foo", the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline. Default is "jquery". [fxn]
-
jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. [fxn]
-
Prototype and Scriptaculous are no longer vendored, they are provided from now on by the prototype-rails gem. [fxn]
-
The scaffold controller will now produce SCSS file if Sass is available [Prem Sichanugrist]
-
The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. [DHH]
-
jQuery is the new default JavaScript library. [fxn]
-
Changed scaffold and app generator to create Ruby 1.9 style hash when running on Ruby 1.9 [Prem Sichanugrist]
So instead of creating something like:
redirect_to users_path, :notice => "User has been created"
it will now be like this:
redirect_to users_path, notice: "User has been created"
You can also passing --old-style-hash
to make Rails generate old style hash even you're on Ruby 1.9
-
Changed scaffold_controller generator to create format block for JSON instead of XML [Prem Sichanugrist]
-
Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) [DHH]
-
Direct logging of Active Record to STDOUT so it's shown inline with the results in the console [DHH]
-
Added
config.force_ssl
configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol [DHH, Prem Sichanugrist, and Josh Peek] -
Added
rails plugin new
command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki] -
Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using
rails new myapp -j jquery
. The default is still Prototype. [siong1987] -
Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim]
-
Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche]
-
Engine is now rack application [Piotr Sarnacki]
-
Added middleware stack to Engine [Piotr Sarnacki]
-
Engine can now load plugins [Piotr Sarnacki]
-
Engine can load its own environment file [Piotr Sarnacki]
-
Added helpers to call engines' route helpers from application and vice versa [Piotr Sarnacki]
-
Task for copying plugins' and engines' migrations to application's db/migrate directory [Piotr Sarnacki]
-
Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki]
-
Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]
-
Include all helpers from plugins and shared engines in application [Piotr Sarnacki]
-
Make sure
escape_js
returns SafeBuffer string if it receives SafeBuffer string [Prem Sichanugrist] -
Fix
escape_js
to work correctly with the new SafeBuffer restriction [Paul Gallagher] -
Brought back alternative convention for namespaced models in i18n [thoefer]
Now the key can be either "namespace.model" or "namespace/model" until further deprecation.
- It is prohibited to perform a in-place SafeBuffer mutation [tenderlove]
The old behavior of SafeBuffer allowed you to mutate string in place via
method like sub!
. These methods can add unsafe strings to a safe buffer,
and the safe buffer will continue to be marked as safe.
An example problem would be something like this:
<%= link_to('hello world', @user).sub!(/hello/, params[:xss]) %>
In the above example, an untrusted string (params[:xss]
) is added to the
safe buffer returned by link_to
, and the untrusted content is successfully
sent to the client without being escaped. To prevent this from happening
sub!
and other similar methods will now raise an exception when they are called on a safe buffer.
In addition to the in-place versions, some of the versions of these methods which return a copy of the string will incorrectly mark strings as safe. For example:
<%= link_to('hello world', @user).sub(/hello/, params[:xss]) %>
The new versions will now ensure that all strings returned by these methods on safe buffers are marked unsafe.
You can read more about this change in http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2e516e7acc96c4fb
-
Warn if we cannot verify CSRF token authenticity [José Valim]
-
Allow AM/PM format in datetime selectors [Aditya Sanghi]
-
Only show dump of regular env methods on exception screen (not all the rack crap) [DHH]
-
auto_link
has been removed with no replacement. If you still useauto_link
please install therails_autolink
gem: http://github.com/tenderlove/rails_autolink [tenderlove] -
Added streaming support, you can enable it with: [José Valim]
class PostsController < ActionController::Base
stream :only => :index
end
Please read the docs at ActionController::Streaming
for more information.
-
Added
ActionDispatch::Request.ignore_accept_header
to ignore accept headers and only consider the format given as parameter [José Valim] -
Created
ActionView::Renderer
and specified an API forActionView::Context
, check those objects for more information [José Valim] -
Added
ActionController::ParamsWrapper
to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default [Prem Sichanugrist]
This can be customized by setting ActionController::Base.wrap_parameters
in config/initializer/wrap_parameters.rb
-
RJS has been extracted out to a gem. [fxn]
-
Implicit actions named not_implemented can be rendered. [Santiago Pastorino]
-
Wildcard route will always match the optional format segment by default. [Prem Sichanugrist]
For example if you have this route:
map '*pages' => 'pages#show'
by requesting '/foo/bar.json', your params[:pages]
will be equals to "foo/bar" with the request format of JSON. If you want the old 3.0.x behavior back, you could supply :format => false
like this:
map '*pages' => 'pages#show', :format => false
- Added
Base.http_basic_authenticate_with
to do simple http basic authentication with a single class method call [DHH]
class PostsController < ApplicationController
USER_NAME, PASSWORD = "dhh", "secret"
before_filter :authenticate, :except => [ :index ]
def index
render :text => "Everyone can see me!"
end
def edit
render :text => "I'm only accessible if you know the password"
end
private
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == USER_NAME && password == PASSWORD
end
end
end
..can now be written as
class PostsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
def index
render :text => "Everyone can see me!"
end
def edit
render :text => "I'm only accessible if you know the password"
end
end
-
Allow you to add
force_ssl
into controller to force browser to transfer data via HTTPS protocol on that particular controller. You can also specify:only
or:except
to specific it to particular action. [DHH and Prem Sichanugrist] -
Allow FormHelper#form_for to specify the :method as a direct option instead of through the :html hash [DHH]
form_for(@post, remote: true, method: :delete) instead of form_for(@post, remote: true, html: { method: :delete })
-
Make
JavaScriptHelper#j()
an alias forJavaScriptHelper#escape_javascript()
-- note this then supersedes theObject#j()
method that the JSON gem adds within templates using the JavaScriptHelper [DHH] -
Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. [Prem Sichanugrist, fxn]
-
URL parameters which return false for to_param now appear in the query string (previously they were removed) [Andrew White]
-
URL parameters which return nil for to_param are now removed from the query string [Andrew White]
-
ActionDispatch::MiddlewareStack
now uses composition over inheritance. It is no longer an array which means there may be methods missing that were not tested. -
Add an
:authenticity_token
option to form_tag for custom handling or to omit the token (pass:authenticity_token => false
). [Jakub Kuźma, Igor Wiedler] -
HTML5
button_tag
helper. [Rizwan Reza] -
Template lookup now searches further up in the inheritance chain. [Artemave]
-
Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki]
-
url_for and named url helpers now accept :subdomain and :domain as options, [Josh Kalderimis]
-
The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis]
-
Added
config.action_controller.include_all_helpers
. By defaulthelper :all
is done inActionController::Base
, which includes all the helpers by default. Settinginclude_all_helpers
to false will result in including onlyapplication_helper
and helper corresponding to controller (likefoo_helper
forfoo_controller
). [Piotr Sarnacki] -
Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:
tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
# => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
Keys are dasherized. Values are JSON-encoded, except for strings and symbols. [Stephen Celis]
-
Deprecate old template handler API. The new API simply requires a template handler to respond to call. [José Valim]
-
:rhtml and :rxml were finally removed as template handlers. [José Valim]
-
Moved etag responsibility from ActionDispatch::Response to the middleware stack. [José Valim]
-
Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects
#get_session
to accept 4 arguments and requires#destroy_session
instead of simply#destroy
. [José Valim] -
file_field automatically adds :multipart => true to the enclosing form. [Santiago Pastorino]
-
Renames
csrf_meta_tag
->csrf_meta_tags
, and aliasescsrf_meta_tag
for backwards compatibility. [fxn] -
Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche]
AR#pluralize_table_names
can be used to singularize/pluralize table name of an individual model:
class User < ActiveRecord::Base
self.pluralize_table_names = false
end
Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names
. [Guillermo Iguaran]
- Add block setting of attributes to singular associations:
class User < ActiveRecord::Base
has_one :account
end
user.build_account{ |a| a.credit_limit => 100.0 }
The block is called after the instance has been initialized. [Andrew White]
-
Add
ActiveRecord::Base.attribute_names
to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. [Prem Sichanugrist] -
CSV Fixtures are deprecated and support will be removed in Rails 3.2.0
-
AR#new
,AR#create
andAR#update_attributes
all accept a second hash as option that allows you to specify which role to consider when assigning attributes. This is built on top of ActiveModel's new mass assignment capabilities:
class Post < ActiveRecord::Base
attr_accessible :title
attr_accessible :title, :published_at, :as => :admin
end
Post.new(params[:post], :as => :admin)
assign_attributes()
with similar API was also added and attributes=(params, guard)
was deprecated.
[Josh Kalderimis]
- default_scope can take a block, lambda, or any other object which responds to
call
for lazy evaluation:
default_scope { ... }
default_scope lambda { ... }
default_scope method(:foo)
This feature was originally implemented by Tim Morgan, but was then removed in favour of defining a default_scope
class method, but has now been added back in by Jon Leighton. The relevant lighthouse ticket is #1812.
- Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via
Model.unscoped
.
Note that this means that if you are inspecting the internal structure of an ActiveRecord::Relation, it will not contain the default scope, though the resulting query will do. You can get a relation containing the default scope by calling ActiveRecord#with_default_scope
, though this is not part of the public API.
[Jon Leighton]
- If you wish to merge default scopes in special ways, it is recommended to define your default scope as a class method and use the standard techniques for sharing code (inheritance, mixins, etc.):
class Post < ActiveRecord::Base
def self.default_scope
where(:published => true).where(:hidden => false)
end
end
[Jon Leighton]
-
PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
-
ConnectionManagement middleware is changed to clean up the connection pool after the rack body has been flushed.
-
Added an
update_column
method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use#update_attribute
unless you are sure you do not want to execute any callback, including the modification of theupdated_at
column. It should not be called on new records.
Example:
User.first.update_column(:name, "sebastian") # => true
[Sebastian Martinez]
-
Associations with a :through option can now use any association as the through or source association, including other associations which have a :through option and has_and_belongs_to_many associations [Jon Leighton]
-
The configuration for the current database connection is now accessible via ActiveRecord::Base.connection_config. [fxn]
-
limits and offsets are removed from COUNT queries unless both are supplied. For example:
People.limit(1).count # => 'SELECT COUNT(*) FROM people'
People.offset(1).count # => 'SELECT COUNT(*) FROM people'
People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
[lighthouse #6262]
- ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called CollectionProxy, which proxies collection associations.
This prevents namespace pollution, separates concerns, and will allow further refactorings.
Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return the associated record or nil. This means that you should not use undocumented methods such as bob.mother.create - use bob.create_mother instead.
[Jon Leighton]
- Make
has_many
:through associations work correctly when you build a record and then save it. This requires you to set the:inverse_of
option on the source reflection on the join model, like so:
class Post < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :post
belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set!
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :posts, :through => :taggings
end
post = Post.first
tag = post.tags.build :name => "ruby"
tag.save # will save a Taggable linking to the post
[Jon Leighton]
-
Support the :dependent option on
has_many :through
associations. For historical and practical reasons,:delete_all
is the default deletion strategy employed byassociation.delete(*records)
, despite the fact that the default strategy is:nullify
for regularhas_many
. Also, this only works at all if the source reflection is abelongs_to
. For other situations, you should directly modify the through association. [Jon Leighton] -
Changed the behavior of association.destroy for has_and_belongs_to_many and has_many :through. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'.
Previously, has_and_belongs_to_many.destroy(*records)
would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table.
Previously, has_many_through.destroy(*records) would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table.
Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations.
If you wish to destroy the records themselves, you can do records.association.each(&:destroy)
[Jon Leighton]
- Add
:bulk => true
option tochange_table
to make all the schema changes defined inchange_table
block using a single ALTER statement. [Pratik Naik]
Example:
change_table(:users, :bulk => true) do |t|
t.string :company_name
t.change :birthdate, :datetime
end
This will now result in:
ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL
-
Removed support for accessing attributes on a
has_and_belongs_to_many
join table. This has been documented as deprecated behavior since April 2006. Please usehas_many :through
instead. [Jon Leighton] -
Added a
create_association!
method for has_one and belongs_to associations. [Jon Leighton] -
Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's
change
method instead of the ordinaryup
anddown
methods. [Prem Sichanugrist] -
Removed support for interpolating string SQL conditions on associations. Instead, you should use a proc, like so:
Before:
has_many :things, :conditions => 'foo = #{bar}'
After:
has_many :things, :conditions => proc { "foo = #{bar}" }
Inside the proc, 'self' is the object which is the owner of the association, unless you are eager loading the association, in which case 'self' is the class which the association is within.
You can have any "normal" conditions inside the proc, so the following will work too:
has_many :things, :conditions => proc { ["foo = ?", bar] }
Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc.
- Added
ActiveRecord::Base#has_secure_password
(viaActiveModel::SecurePassword
) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example:
# Schema: User(name:string, password_digest:string, password_salt:string)
class User < ActiveRecord::Base
has_secure_password
end
user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
user.save # => false, password required
user.password = "mUc3m00RsqyRe"
user.save # => false, confirmation doesn't match
user.password_confirmation = "mUc3m00RsqyRe"
user.save # => true
user.authenticate("notright") # => false
user.authenticate("mUc3m00RsqyRe") # => user
User.find_by_name("david").try(:authenticate, "notright") # => nil
User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
- When a model is generated
add_index
is added by default for belongs_to or references columns
rails g model post user:belongs_to will generate the following:
class CreatePosts < ActiveRecord::Migration
def up
create_table :posts do |t|
t.belongs_to :user
t.timestamps
end
add_index :posts, :user_id
end
def down
drop_table :posts
end
end
[Santiago Pastorino]
-
Setting the id of a belongs_to object will update the reference to the object. [#2989 state:resolved]
-
ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics.
-
Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.
-
Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.
-
Migrations can be defined as reversible, meaning that the migration system will figure out how to reverse your migration. To use reversible migrations, mjust define the "change" method. For example:
class MyMigration < ActiveRecord::Migration
def change
create_table(:horses) do
t.column :content, :text
t.column :remind_at, :datetime
end
end
end
Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define 'up' and 'down' in your migration. If you define something in change
that cannot be reversed, an IrreversibleMigration exception will be raised when going down.
- Migrations should use instance methods rather than class methods:
class FooMigration < ActiveRecord::Migration
def up
...
end
end
[Aaron Patterson]
-
has_one
maintains the association with separateafter_create
/after_update
instead of a single after_save. [fxn] -
The following code:
Model.limit(10).scoping { Model.count }
now generates the following SQL:
SELECT COUNT(*) FROM models LIMIT 10
This may not return what you want. Instead, you may with to do something like this:
Model.limit(10).scoping { Model.all.size }
[Aaron Patterson]
-
attr_accessible and friends now accepts :as as option to specify a role [Josh Kalderimis]
-
Add support for proc or lambda as an option for InclusionValidator, ExclusionValidator, and FormatValidator [Prem Sichanugrist]
You can now supply Proc, lambda, or anything that respond to #call in those validations, and it will be called with current record as an argument. That given proc or lambda must returns an object which respond to #include?
for InclusionValidator and ExclusionValidator, and returns a regular expression object for FormatValidator.
-
Added
ActiveModel::SecurePassword
to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH] -
ActiveModel::AttributeMethods
allows attributes to be defined on demand [Alexander Uvarov]
-
ActiveSupport::Dependencies
now raises NameError if it finds an existing constant inload_missing_constant
. This better reflects the nature of the error which is usually caused by calling constantize on a nested constant. [Andrew White] -
Deprecated
ActiveSupport::SecureRandom
in favor of SecureRandom from the standard library [Jon Leighton] -
New reporting method
Kernel#quietly
. [fxn] -
Add
String#inquiry
as a convenience method for turning a string into aStringInquirer
object [DHH] -
Add
Object#in?
to test if an object is included in another object [Prem Sichanugrist, Brian Morearty, John Reitano] -
LocalCache strategy is now a real middleware class, not an anonymous class posing for pictures.
-
ActiveSupport::Dependencies::ClassCache class has been introduced for holding references to reloadable classes.
-
ActiveSupport::Dependencies::Reference has been refactored to take direct advantage of the new ClassCache.
-
Backports
Range#cover?
as an alias for Range#include? in Ruby 1.8 [Diego Carrion, fxn] -
Added
weeks_ago
andprev_week
to Date/DateTime/Time. [Rob Zolkos, fxn] -
Added
before_remove_const
callback toActiveSupport::Dependencies.remove_unloadable_constants!
[Andrew White]
- The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set
self.format = :xml
in the class. eg.
class User < ActiveResource::Base
self.format = :xml
end
- No changes
Awesome. Nice work guys.