Merge branch 'master' of github.com:lifo/docrails

Conflicts:
	guides/source/upgrading_ruby_on_rails.md
This commit is contained in:
Vijay Dev 2013-06-14 01:14:56 +05:30
commit 41a398f859
58 changed files with 332 additions and 169 deletions

@ -170,8 +170,8 @@
*Olek Janiszewski*
* fixes bug introduced by #3329. Now, when autosaving associations,
deletions happen before inserts and saves. This prevents a 'duplicate
* fixes bug introduced by #3329. Now, when autosaving associations,
deletions happen before inserts and saves. This prevents a 'duplicate
unique value' database error that would occur if a record being created had
the same value on a unique indexed field as that of a record being destroyed.

@ -200,13 +200,14 @@ def set_owner_attributes(record)
creation_attributes.each { |key, value| record[key] = value }
end
# Should be true if there is a foreign key present on the owner which
# Returns true if there is a foreign key present on the owner which
# references the target. This is used to determine whether we can load
# the target if the owner is currently a new record (and therefore
# without a key).
# without a key). If the owner is a new record then foreign_key must
# be present in order to load target.
#
# Currently implemented by belongs_to (vanilla and polymorphic) and
# has_one/has_many :through associations which go through a belongs_to
# has_one/has_many :through associations which go through a belongs_to.
def foreign_key_present?
false
end

@ -50,7 +50,7 @@ def reset_counters(id, *counters)
# ==== Parameters
#
# * +id+ - The id of the object you wish to update a counter on or an Array of ids.
# * +counters+ - An Array of Hashes containing the names of the fields
# * +counters+ - A Hash containing the names of the fields
# to update as keys and the amount to update the field by as values.
#
# ==== Examples

@ -5,7 +5,7 @@ module Inheritance
extend ActiveSupport::Concern
included do
# Determine whether to store the full constant name including namespace when using STI
# Determines whether to store the full constant name including namespace when using STI.
class_attribute :store_full_sti_class, instance_writer: false
self.store_full_sti_class = true
end
@ -13,7 +13,7 @@ module Inheritance
module ClassMethods
# Determines if one of the attributes passed in is the inheritance column,
# and if the inheritance column is attr accessible, it initializes an
# instance of the given subclass instead of the base class
# instance of the given subclass instead of the base class.
def new(*args, &block)
if abstract_class? || self == Base
raise NotImplementedError, "#{self} is an abstract class and can not be instantiated."
@ -27,7 +27,8 @@ def new(*args, &block)
super
end
# True if this isn't a concrete subclass needing a STI type condition.
# Returns +true+ if this does not need STI type condition. Returns
# +false+ if STI type condition needs to be applied.
def descends_from_active_record?
if self == Base
false

@ -11,7 +11,7 @@ module Batches
# The #find_each method uses #find_in_batches with a batch size of 1000 (or as
# specified by the +:batch_size+ option).
#
# Person.all.find_each do |person|
# Person.find_each do |person|
# person.do_awesome_stuff
# end
#
@ -19,8 +19,26 @@ module Batches
# person.party_all_night!
# end
#
# You can also pass the +:start+ option to specify
# an offset to control the starting point.
# ==== Options
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
# This is especially useful if you want multiple workers dealing with
# the same processing queue. You can make worker 1 handle all the records
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
# (by setting the +:start+ option on that worker).
#
# # Let's process for a batch of 2000 records, skiping the first 2000 rows
# Person.find_each(start: 2000, batch_size: 2000) do |person|
# person.party_all_night!
# end
#
# NOTE: It's not possible to set the order. That is automatically set to
# ascending on the primary key ("id ASC") to make the batch ordering
# work. This also means that this method only works with integer-based
# primary keys.
#
# NOTE: You can't set the limit either, that's used to control
# the batch sizes.
def find_each(options = {})
find_in_batches(options) do |records|
records.each { |record| yield record }
@ -28,31 +46,33 @@ def find_each(options = {})
end
# Yields each batch of records that was found by the find +options+ as
# an array. The size of each batch is set by the +:batch_size+
# option; the default is 1000.
#
# You can control the starting point for the batch processing by
# supplying the +:start+ option. This is especially useful if you
# want multiple workers dealing with the same processing queue. You can
# make worker 1 handle all the records between id 0 and 10,000 and
# worker 2 handle from 10,000 and beyond (by setting the +:start+
# option on that worker).
#
# It's not possible to set the order. That is automatically set to
# ascending on the primary key ("id ASC") to make the batch ordering
# work. This also means that this method only works with integer-based
# primary keys. You can't set the limit either, that's used to control
# the batch sizes.
# an array.
#
# Person.where("age > 21").find_in_batches do |group|
# sleep(50) # Make sure it doesn't get too crowded in there!
# group.each { |person| person.party_all_night! }
# end
#
# ==== Options
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
# This is especially useful if you want multiple workers dealing with
# the same processing queue. You can make worker 1 handle all the records
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
# (by setting the +:start+ option on that worker).
#
# # Let's process the next 2000 records
# Person.all.find_in_batches(start: 2000, batch_size: 2000) do |group|
# Person.find_in_batches(start: 2000, batch_size: 2000) do |group|
# group.each { |person| person.party_all_night! }
# end
#
# NOTE: It's not possible to set the order. That is automatically set to
# ascending on the primary key ("id ASC") to make the batch ordering
# work. This also means that this method only works with integer-based
# primary keys.
#
# NOTE: You can't set the limit either, that's used to control
# the batch sizes.
def find_in_batches(options = {})
options.assert_valid_keys(:start, :batch_size)

@ -11,9 +11,11 @@ module FinderMethods
# Person.find([1]) # returns an array for the object with ID = 1
# Person.where("administrator = 1").order("created_on DESC").find(1)
#
# Note that returned records may not be in the same order as the ids you
# provide since database rows are unordered. Give an explicit <tt>order</tt>
# to ensure the results are sorted.
# <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
#
# NOTE: The returned records may not be in the same order as the ids you
# provide since database rows are unordered. You'd need to provide an explicit <tt>order</tt>
# option if you want the results are sorted.
#
# ==== Find with lock
#
@ -28,6 +30,34 @@ module FinderMethods
# person.visits += 1
# person.save!
# end
#
# ==== Variations of +find+
#
# Person.where(name: 'Spartacus', rating: 4)
# # returns a chainable list (which can be empty).
#
# Person.find_by(name: 'Spartacus', rating: 4)
# # returns the first item or nil.
#
# Person.where(name: 'Spartacus', rating: 4).first_or_initialize
# # returns the first item or returns a new instance (requires you call .save to persist against the database).
#
# Person.where(name: 'Spartacus', rating: 4).first_or_create
# # returns the first item or creates it and returns it, available since Rails 3.2.1.
#
# ==== Alternatives for +find+
#
# Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
# # returns a boolean indicating if any record with the given conditions exist.
#
# Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
# # returns a chainable list of instances with only the mentioned fields.
#
# Person.where(name: 'Spartacus', rating: 4).ids
# # returns an Array of ids, available since Rails 3.2.1.
#
# Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
# # returns an Array of the required fields, available since Rails 3.1.
def find(*args)
if block_given?
to_a.find { |*block_args| yield(*block_args) }
@ -79,6 +109,19 @@ def take!
# Person.where(["user_name = :u", { u: user_name }]).first
# Person.order("created_on DESC").offset(5).first
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
#
# ==== Rails 3
#
# Person.first # SELECT "people".* FROM "people" LIMIT 1
#
# NOTE: Rails 3 may not order this query by the primary key and the order
# will depend on the database implementation. In order to ensure that behavior,
# use <tt>User.order(:id).first</tt> instead.
#
# ==== Rails 4
#
# Person.first # SELECT "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT 1
#
def first(limit = nil)
if limit
if order_values.empty? && primary_key

@ -13,17 +13,17 @@ module ActiveSupport
# can focus on the rest.
#
# bc = BacktraceCleaner.new
# bc.add_filter { |line| line.gsub(Rails.root, '') }
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
# bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
# bc.add_filter { |line| line.gsub(Rails.root, '') } # strip the Rails.root prefix
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
# bc.clean(exception.backtrace) # perform the cleanup
#
# To reconfigure an existing BacktraceCleaner (like the default one in Rails)
# and show as much data as possible, you can always call
# <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
# backtrace to a pristine state. If you need to reconfigure an existing
# BacktraceCleaner so that it does not filter or modify the paths of any lines
# of the backtrace, you can call BacktraceCleaner#remove_filters! These two
# methods will give you a completely untouched backtrace.
# of the backtrace, you can call <tt>BacktraceCleaner#remove_filters!<tt>
# These two methods will give you a completely untouched backtrace.
#
# Inspired by the Quiet Backtrace gem by Thoughtbot.
class BacktraceCleaner

@ -228,7 +228,7 @@ def self.instrument
#
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
# a cache entry is used very frequently and is under heavy load. If a
# cache expires and due to heavy load seven different processes will try
# cache expires and due to heavy load several different processes will try
# to read data natively and then they all will try to write to cache. To
# avoid that case the first process to find an expired cache entry will
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.

@ -143,8 +143,8 @@ module ActiveSupport
#
# == Default Queue
#
# Notifications ships with a queue implementation that consumes and publish events
# to log subscribers in a thread. You can use any queue implementation you want.
# Notifications ships with a queue implementation that consumes and publishes events
# to all log subscribers. You can use any queue implementation you want.
#
module Notifications
class << self

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 B

After

Width:  |  Height:  |  Size: 35 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 B

After

Width:  |  Height:  |  Size: 36 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 B

After

Width:  |  Height:  |  Size: 36 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 290 B

After

Width:  |  Height:  |  Size: 176 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 322 B

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 B

After

Width:  |  Height:  |  Size: 188 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 340 B

After

Width:  |  Height:  |  Size: 191 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

@ -40,7 +40,7 @@ Here's a summary of the rack-related changes:
* `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', ...`.
* 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.
### Renewed Support for Rails Engines
@ -173,8 +173,8 @@ before_save :update_credit_rating, :if => :active,
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")
developers = Developer.find(:all, :group => "salary",
:having => "sum(salary) > 10000", :select => "salary")
```
* Lead Contributor: [Emilio Tagua](http://github.com/miloops)

@ -83,7 +83,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railt
### Notable changes
* New test locations `test/models`, `test/helpers`, `test/controllers`, and `test/mailers`. Corresponding rake tasks added as well. ([Pull Request](https://github.com/rails/rails/pull/7878))
* New test locations `test/models`, `test/helpers`, `test/controllers`, and `test/mailers`. Corresponding rake tasks added as well. ([Pull Request](https://github.com/rails/rails/pull/7878))
* Your app's executables now live in the `bin/` directory. Run `rake rails:update:bin` to get `bin/bundle`, `bin/rails`, and `bin/rake`.
@ -111,10 +111,9 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ
### Notable changes
* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to protect attributes from mass assignment when non-permitted attributes are passed.
* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to protect attributes from mass assignment when non-permitted attributes are passed.
* Added `ActiveModel::Model`, a mixin to make Ruby objects work with
Action Pack out of box.
* Added `ActiveModel::Model`, a mixin to make Ruby objects work with Action Pack out of box.
### Deprecations
@ -125,27 +124,27 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ
### Notable changes
* Replace deprecated `memcache-client` gem with `dalli` in ActiveSupport::Cache::MemCacheStore.
* Replace deprecated `memcache-client` gem with `dalli` in ActiveSupport::Cache::MemCacheStore.
* Optimize ActiveSupport::Cache::Entry to reduce memory and processing overhead.
* Optimize ActiveSupport::Cache::Entry to reduce memory and processing overhead.
* Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument.
* Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument.
* `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!`.
* `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!`.
### Deprecations
* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from MiniTest instead.
* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from MiniTest instead.
* ActiveSupport::Benchmarkable#silence has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1.
* ActiveSupport::Benchmarkable#silence has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1.
* `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals.
* `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals.
* Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols).
* Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols).
* BufferedLogger is deprecated. Use ActiveSupport::Logger, or the logger from Ruby standard library.
* BufferedLogger is deprecated. Use ActiveSupport::Logger, or the logger from Ruby standard library.
* Deprecate `assert_present` and `assert_blank` in favor of `assert object.blank?` and `assert object.present?`
* Deprecate `assert_present` and `assert_blank` in favor of `assert object.blank?` and `assert object.present?`
Action Pack
-----------
@ -166,7 +165,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ
### Notable changes
* Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.
* Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.
* The methods `drop_table` and `remove_column` are now reversible, as long as the necessary information is given.
The method `remove_column` used to accept multiple column names; instead use `remove_columns` (which is not revertible).
@ -179,36 +178,36 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ
If migrating down, the given migration / block is run normally.
See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#reverting-previous-migrations)
* Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support.
* Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support.
* Add `Relation#load` to explicitly load the record and return `self`.
* Add `Relation#load` to explicitly load the record and return `self`.
* `Model.all` now returns an `ActiveRecord::Relation`, rather than an array of records. Use `Relation#to_a` if you really want an array. In some specific cases, this may cause breakage when upgrading.
* `Model.all` now returns an `ActiveRecord::Relation`, rather than an array of records. Use `Relation#to_a` if you really want an array. In some specific cases, this may cause breakage when upgrading.
* Added `ActiveRecord::Migration.check_pending!` that raises an error if migrations are pending.
* Added `ActiveRecord::Migration.check_pending!` that raises an error if migrations are pending.
* Added custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this:
* Added custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this:
store :settings, accessors: [ :color, :homepage ], coder: JSON
* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`.
* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`.
* Remove IdentityMap.
* Remove IdentityMap.
* Remove automatic execution of EXPLAIN queries. The option `active_record.auto_explain_threshold_in_seconds` is no longer used and should be removed.
* Remove automatic execution of EXPLAIN queries. The option `active_record.auto_explain_threshold_in_seconds` is no longer used and should be removed.
* Adds `ActiveRecord::NullRelation` and `ActiveRecord::Relation#none` implementing the null object pattern for the Relation class.
* Adds `ActiveRecord::NullRelation` and `ActiveRecord::Relation#none` implementing the null object pattern for the Relation class.
* Added `create_join_table` migration helper to create HABTM join tables.
* Added `create_join_table` migration helper to create HABTM join tables.
* Allows PostgreSQL hstore records to be created.
* Allows PostgreSQL hstore records to be created.
### Deprecations
* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.
* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.
* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's
how you can rewrite the code:
* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's
how you can rewrite the code:
* `find_all_by_...` can be rewritten using `where(...)`.
* `find_last_by_...` can be rewritten using `where(...).last`.

@ -257,7 +257,7 @@ params.require(:log_entry).permit!
```
This will mark the `:log_entry` parameters hash and any subhash of it
permitted. Extreme care should be taken when using `permit!` as it
permitted. Extreme care should be taken when using `permit!` as it
will allow all current and future model attributes to be
mass-assigned.

@ -496,7 +496,7 @@ end
There may be cases in which you want to skip the template rendering step and
supply the email body as a string. You can achieve this using the `:body`
option. In such cases don't forget to add the `:content_type` option. Rails
option. In such cases don't forget to add the `:content_type` option. Rails
will default to `text/plain` otherwise.
```ruby
@ -623,7 +623,7 @@ files (environment.rb, production.rb, etc...)
| Configuration | Description |
|---------------|-------------|
|`logger`|Generates 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:<ul><li>`:address` - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>`:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>`:domain` - If you need to specify a HELO domain, you can do it here.</li><li>`:user_name` - If your mail server requires authentication, set the username in this setting.</li><li>`:password` - If your mail server requires authentication, set the password in this setting.</li><li>`: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`.</li><li>`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.</li></ul>|
|`smtp_settings`|Allows detailed configuration for `:smtp` delivery method:<ul><li>`:address` - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>`:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>`:domain` - If you need to specify a HELO domain, you can do it here.</li><li>`:user_name` - If your mail server requires authentication, set the username in this setting.</li><li>`:password` - If your mail server requires authentication, set the password in this setting.</li><li>`: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`.</li><li>`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.</li></ul>|
|`sendmail_settings`|Allows you to override options for the `:sendmail` delivery method.<ul><li>`:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`.</li><li>`:arguments` - The command line arguments to be passed to sendmail. Defaults to `-i -t`.</li></ul>|
|`raise_delivery_errors`|Whether or not errors should be raised if the email fails to be delivered. This only works if the external email server is configured for immediate delivery.|
|`delivery_method`|Defines a delivery method. Possible values are `:smtp` (default), `:sendmail`, `:file` and `:test`.|
@ -649,7 +649,7 @@ config.action_mailer.delivery_method = :sendmail
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: 'no-replay@example.com'}
config.action_mailer.default_options = {from: 'no-reply@example.com'}
```
### Action Mailer Configuration for Gmail

@ -62,9 +62,9 @@ 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 Active Record 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.
you configure your applications in the very same way most of the time then this
should be the default way. Thus, explicit configuration would be needed
only in those cases where you can't follow the standard convention.
### Naming Conventions

@ -91,7 +91,7 @@ The primary operation of `Model.find(options)` can be summarized as:
### Retrieving a Single Object
Active Record provides five different ways of retrieving a single object.
Active Record provides several different ways of retrieving a single object.
#### Using a Primary Key
@ -1230,7 +1230,7 @@ One important caveat is that `default_scope` will be overridden by
```ruby
class User < ActiveRecord::Base
default_scope { where state: 'pending' }
default_scope { where state: 'pending' }
scope :active, -> { where state: 'active' }
scope :inactive, -> { where state: 'inactive' }
end

@ -243,7 +243,7 @@ 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
`: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.
@ -677,13 +677,13 @@ class GoodnessValidator
def initialize(person)
@person = person
end
def validate
if some_complex_condition_involving_ivars_and_private_methods?
@person.errors[:base] << "This person is evil"
end
end
# …
end
```
@ -736,8 +736,8 @@ class Topic < ActiveRecord::Base
validates :title, length: { is: 5 }, allow_blank: true
end
Topic.create("title" => "").valid? # => true
Topic.create("title" => nil).valid? # => true
Topic.create(title: "").valid? # => true
Topic.create(title: nil).valid? # => true
```
### `:message`

@ -418,6 +418,14 @@ TIP: Since `with_options` forwards calls to its receiver they can be nested. Eac
NOTE: Defined in `active_support/core_ext/object/with_options.rb`.
### JSON support
Active Support provides a better implemention of `to_json` than the +json+ gem ordinarily provides for Ruby objects. This is because some classes, like +Hash+ and +OrderedHash+ needs special handling in order to provide a proper JSON representation.
Active Support also provides an implementation of `as_json` for the <tt>Process::Status</tt> class.
NOTE: Defined in `active_support/core_ext/object/to_json.rb`.
### Instance Variables
Active Support provides several methods to ease access to instance variables.
@ -439,6 +447,22 @@ C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
#### `instance_variable_names`
The method `instance_variable_names` returns an array. Each name includes the "@" sign.
```ruby
class C
def initialize(x, y)
@x, @y = x, y
end
end
C.new(0, 1).instance_variable_names # => ["@x", "@y"]
```
NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
### Silencing Warnings, Streams, and Exceptions
The methods `silence_warnings` and `enable_warnings` change the value of `$VERBOSE` accordingly for the duration of their block, and reset it afterwards:
@ -1038,7 +1062,7 @@ For convenience `class_attribute` also defines an instance predicate which is th
When `:instance_reader` is `false`, the instance predicate returns a `NoMethodError` just like the reader method.
If you do not want the instance predicate, pass `instance_predicate: false` and it will not be defined.
If you do not want the instance predicate, pass `instance_predicate: false` and it will not be defined.
NOTE: Defined in `active_support/core_ext/class/attribute.rb`
@ -1423,7 +1447,7 @@ The method `pluralize` returns the plural of its receiver:
As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in `config/initializers/inflections.rb`. That file is generated by the `rails` command and has instructions in comments.
`pluralize` can also take an optional `count` parameter. If `count == 1` the singular form will be returned. For any other value of `count` the plural form will be returned:
`pluralize` can also take an optional `count` parameter. If `count == 1` the singular form will be returned. For any other value of `count` the plural form will be returned:
```ruby
"dude".pluralize(0) # => "dudes"
@ -2011,8 +2035,33 @@ NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
Extensions to `BigDecimal`
--------------------------
### `to_s`
...
The method `to_s` is aliased to `to_formatted_s`. This provides a convenient way to display a BigDecimal value in floating-point notation:
```ruby
BigDecimal.new(5.00, 6).to_s # => "5.0"
```
### `to_formatted_s`
Te method `to_formatted_s` provides a default specifier of "F". This means that a simple call to `to_formatted_s` or `to_s` will result in floating point representation instead of engineering notation:
```ruby
BigDecimal.new(5.00, 6).to_formatted_s # => "5.0"
```
and that symbol specifiers are also supported:
```ruby
BigDecimal.new(5.00, 6).to_formatted_s(:db) # => "5.0"
```
Engineering notation is still supported:
```ruby
BigDecimal.new(5.00, 6).to_formatted_s("e") # => "0.5E1"
```
Extensions to `Enumerable`
--------------------------

@ -25,7 +25,7 @@ Write in present tense: "Returns a hash that...", rather than "Returned a hash t
Start comments in upper case. Follow regular punctuation rules:
```ruby
# Declares an attribute reader backed by an internally-named
# Declares an attribute reader backed by an internally-named
# instance variable.
def attr_internal_reader(*attrs)
...
@ -57,7 +57,7 @@ Use two spaces to indent chunks of code--that is, for markup purposes, two space
Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:
```ruby
# Converts a collection of elements into a formatted string by
# Converts a collection of elements into a formatted string by
# calling +to_s+ on all elements and joining them.
#
# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
@ -141,7 +141,7 @@ class Array
end
```
WARNING: Using a pair of `+...+` for fixed-width font only works with **words**; that is: anything matching `\A\w+\z`. For anything else use `<tt>...</tt>`, notably symbols, setters, inline snippets, etc.
WARNING: Using a pair of `+...+` for fixed-width font only works with **words**; that is: anything matching `\A\w+\z`. For anything else use `<tt>...</tt>`, notably symbols, setters, inline snippets, etc.
### Regular Font

@ -721,6 +721,7 @@ When you declare a `belongs_to` association, the declaring class automatically g
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
* `create_association!(attributes = {})`
In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
@ -737,6 +738,7 @@ customer
customer=
build_customer
create_customer
create_customer!
```
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
@ -777,6 +779,10 @@ The `create_association` method returns a new object of the associated type. Thi
customer_name: "John Doe")
```
##### `create_association!(attributes = {})`
Does the same as <tt>create_association</tt> above, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid.
#### Options for `belongs_to`
@ -1019,6 +1025,7 @@ When you declare a `has_one` association, the declaring class automatically gain
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
* `create_association!(attributes = {})`
In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:
@ -1035,6 +1042,7 @@ account
account=
build_account
create_account
create_account!
```
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
@ -1073,6 +1081,10 @@ The `create_association` method returns a new object of the associated type. Thi
@account = @supplier.create_account(terms: "Net 30")
```
##### `create_association!(attributes = {})`
Does the same as <tt>create_association</tt> above, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid.
#### Options for `has_one`
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_one` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
@ -1285,6 +1297,7 @@ When you declare a `has_many` association, the declaring class automatically gai
* `collection.exists?(...)`
* `collection.build(attributes = {}, ...)`
* `collection.create(attributes = {})`
* `collection.create!(attributes = {})`
In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
@ -1312,6 +1325,7 @@ orders.where(...)
orders.exists?(...)
orders.build(attributes = {}, ...)
orders.create(attributes = {})
orders.create!(attributes = {})
```
##### `collection(force_reload = false)`
@ -1427,6 +1441,10 @@ The `collection.create` method returns a new object of the associated type. This
order_number: "A12345")
```
##### `collection.create!(attributes = {})`
Does the same as <tt>collection.create</tt> above, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid.
#### Options for `has_many`
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
@ -1511,6 +1529,20 @@ end
By convention, Rails assumes 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.
Let's say that `users` table has `id` as the primary_key but it also has
`guid` column. And the requirement is that `todos` table should hold
`guid` column value and not `id` value. This can be achieved like this
```ruby
class User < ActiveRecord::Base
has_many :todos, primary_key: :guid
end
```
Now if we execute `@user.todos.create` then `@todo` record will have
`user_id` value as the `guid` value of `@user`.
##### `: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.
@ -1678,7 +1710,7 @@ person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
```
In the above case there are two readings and `person.posts` brings out both of
In the above case there are two readings and `person.posts` brings out both of
them even though these records are pointing to the same post.
Now let's set `distinct`:
@ -1697,24 +1729,24 @@ person.posts.inspect # => [#<Post id: 7, name: "a1">]
Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
```
In the above case there are still two readings. However `person.posts` shows
In the above case there are still two readings. However `person.posts` shows
only one post because the collection loads only unique records.
If you want to make sure that, upon insertion, all of the records in the
persisted association are distinct (so that you can be sure that when you
inspect the association that you will never find duplicate records), you should
add a unique index on the table itself. For example, if you have a table named
``person_posts`` and you want to make sure all the posts are unique, you could
If you want to make sure that, upon insertion, all of the records in the
persisted association are distinct (so that you can be sure that when you
inspect the association that you will never find duplicate records), you should
add a unique index on the table itself. For example, if you have a table named
``person_posts`` and you want to make sure all the posts are unique, you could
add the following in a migration:
```ruby
add_index :person_posts, :post, :unique => true
```
Note that checking for uniqueness using something like ``include?`` is subject
to race conditions. Do not attempt to use ``include?`` to enforce distinctness
in an association. For instance, using the post example from above, the
following code would be racy because multiple users could be attempting this
Note that checking for uniqueness using something like ``include?`` is subject
to race conditions. Do not attempt to use ``include?`` to enforce distinctness
in an association. For instance, using the post example from above, the
following code would be racy because multiple users could be attempting this
at the same time:
```ruby
@ -1754,6 +1786,7 @@ When you declare a `has_and_belongs_to_many` association, the declaring class au
* `collection.exists?(...)`
* `collection.build(attributes = {})`
* `collection.create(attributes = {})`
* `collection.create!(attributes = {})`
In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
@ -1781,6 +1814,7 @@ assemblies.where(...)
assemblies.exists?(...)
assemblies.build(attributes = {}, ...)
assemblies.create(attributes = {})
assemblies.create!(attributes = {})
```
##### Additional Column Methods
@ -1900,6 +1934,10 @@ The `collection.create` method returns a new object of the associated type. This
@assembly = @part.assemblies.create({assembly_name: "Transmission housing"})
```
##### `collection.create!(attributes = {})`
Does the same as <tt>collection.create</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid.
#### Options for `has_and_belongs_to_many`
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_and_belongs_to_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
@ -1928,7 +1966,7 @@ TIP: The `:foreign_key` and `:association_foreign_key` options are useful when s
```ruby
class User < ActiveRecord::Base
has_and_belongs_to_many :friends,
has_and_belongs_to_many :friends,
class_name: "User",
foreign_key: "this_user_id",
association_foreign_key: "other_user_id"
@ -2161,4 +2199,4 @@ Extensions can refer to the internals of the association proxy using these three
* `proxy_association.owner` returns the object that the association is a part of.
* `proxy_association.reflection` returns the reflection object that describes the association.
* `proxy_association.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`.
* `proxy_association.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`.

@ -104,6 +104,15 @@ This method generates a cache key that depends on all products and can be used i
All available products:
<% end %>
```
If you want to cache a fragment under certain condition you can use `cache_if` or `cache_unless`
```erb
<% cache_if (condition, cache_key_for_products) do %>
All available products:
<% end %>
```
You can also use an Active Record model as the cache key:
```erb
@ -236,7 +245,7 @@ config.cache_store = :ehcache_store
When initializing the cache, you may use the `:ehcache_config` option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
| Property | Argument Type | Description |
| --------------------------- | ------------------- | ----------------------------------------------------------- |

@ -30,10 +30,10 @@ Configuring Rails Components
In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file `config/application.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 `config/application.rb` file includes this setting:
For example, the `config/application.rb` file includes this setting:
```ruby
config.filter_parameters += [:password]
config.autoload_paths += %W(#{config.root}/extras)
```
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 in `config/application.rb`:
@ -97,7 +97,9 @@ These configuration methods are to be called on a `Rails::Railtie` object, such
* `config.file_watcher` the class used to detect file updates in the filesystem when `config.reload_classes_only_on_change` is true. Must conform to `ActiveSupport::FileUpdateChecker` API.
* `config.filter_parameters` used for filtering out the parameters that you don't want shown in the logs, such as passwords or credit card numbers.
* `config.filter_parameters` used for filtering out the parameters that
you don't want shown in the logs, such as passwords or credit card
numbers. New applications filter out passwords by adding the following `config.filter_parameters+=[:password]` in `config/initializers/filter_parameter_logging.rb`.
* `config.force_ssl` forces all requests to be under HTTPS protocol by using `ActionDispatch::SSL` middleware.
@ -131,7 +133,8 @@ These configuration methods are to be called on a `Rails::Railtie` object, such
### Configuring Assets
* `config.assets.enabled` a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in `config/application.rb`.
* `config.assets.enabled` a flag that controls whether the asset
pipeline is enabled. It is set to true by default.
* `config.assets.compress` a flag that enables the compression of compiled assets. It is explicitly set to true in `config/production.rb`.
@ -421,13 +424,13 @@ There are a few configuration options available in Active Support:
### Configuring a Database
Just about every Rails application will interact with a database. The database to use is specified in a configuration file called `config/database.yml`. If you open this file in a new Rails application, you'll see a default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default:
Just about every Rails application will interact with a database. The database to use is specified in a configuration file called `config/database.yml`. If you open this file in a new Rails application, you'll see a default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default:
* The `development` environment is used on your development/local computer as you interact manually with the application.
* The `test` environment is used when running automated tests.
* The `production` environment is used when you deploy your application for the world to use.
TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the `config/database.yml` file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.
TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the `config/database.yml` file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.
#### Configuring an SQLite3 Database
@ -527,7 +530,7 @@ By default Rails ships with three environments: "development", "test", and "prod
Imagine you have a server which mirrors the production environment but is only used for testing. Such a server is commonly called a "staging server". To define an environment called "staging" for this server just by create a file called `config/environments/staging.rb`. Please use the contents of any existing file in `config/environments` as a starting point and make the necessary changes from there.
That environment is no different than the default ones, start a server with `rails server -e staging`, a console with `rails console staging`, `Rails.env.staging?` works, etc.
That environment is no different than the default ones, start a server with `rails server -e staging`, a console with `rails console staging`, `Rails.env.staging?` works, etc.
Rails Environment Settings

@ -568,7 +568,7 @@ NOTE: In many cases the built-in date pickers are clumsy as they do not aid the
### 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 overridden 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.
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 overridden 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
@ -830,7 +830,7 @@ Many apps grow beyond simple forms editing a single object. For example when cre
### Configuring the Model
Active Record provides model level support via the `accepts_nested_attributes_for` method:
Active Record provides model level support via the `accepts_nested_attributes_for` method:
```ruby
class Person < ActiveRecord::Base
@ -885,7 +885,7 @@ end
:name => 'John Doe',
:addresses_attributes => {
'0' => {
:kind => 'Home',
:kind => 'Home',
:street => '221b Baker Street',
},
'1' => {

@ -135,7 +135,7 @@ application. Most of the work in this tutorial will happen in the `app/` folder,
| ----------- | ------- |
|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
|bin/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
|config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html)|
|config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html)|
|config.ru|Rack configuration for Rack based servers used to start the application.|
|db/|Contains your current database schema, as well as the database migrations.|
|Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) |
@ -264,7 +264,7 @@ Blog::Application.routes.draw do
end
```
If you run `rake routes`, you'll see that all the routes for the
If you run `rake routes`, you'll see that all the routes for the
standard RESTful actions.
```bash
@ -288,7 +288,7 @@ It will look a little basic for now, but that's ok. We'll look at improving the
### Laying down the ground work
The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. With the route already defined, requests can now be made to `/posts/new` in the application. Navigate to <http://localhost:3000/posts/new> and you'll see a routing error:
The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. With the route already defined, requests can now be made to `/posts/new` in the application. Navigate to <http://localhost:3000/posts/new> and you'll see a routing error:
![Another routing error, uninitialized constant PostsController](images/getting_started/routing_error_no_controller.png)
@ -560,14 +560,14 @@ whether the model was saved or not.
If you submit the form again now, Rails will complain about not finding
the `show` action. That's not very useful though, so let's add the
`show` action before proceeding.
`show` action before proceeding.
```ruby
post GET /posts/:id(.:format) posts#show
```
The special syntax `:id` tells rails that this route expects an `:id`
parameter, which in our case will be the id of the post.
parameter, which in our case will be the id of the post.
As we did before, we need to add the `show` action in
`app/controllers/posts_controller.rb` and its respective view.
@ -628,7 +628,7 @@ Visit <http://localhost:3000/posts/new> and give it a try!
### Listing all posts
We still need a way to list all our posts, so let's do that.
We still need a way to list all our posts, so let's do that.
We'll use a specific route from `config/routes.rb`:
```ruby
@ -749,7 +749,7 @@ end
```
These changes will ensure that all posts have a title that is at least five
characters long. Rails can validate a variety of conditions in a model,
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. Validations are covered in detail in [Active
Record Validations](active_record_validations.html)
@ -770,7 +770,7 @@ def create
@post = Post.new(params[:post].permit(:title, :text))
if @post.save
redirect_to @post
redirect_to @post
else
render 'new'
end
@ -1091,7 +1091,7 @@ together.
</table>
```
Here we're using `link_to` in a different way. We pass the named route as the first argument,
Here we're using `link_to` in a different way. We pass the named route as the first argument,
and then the final two keys as another argument. The `:method` and `:'data-confirm'`
options are used as HTML5 attributes so that when the link is clicked,
Rails will first show a confirm dialog to the user, and then submit the link with method `delete`.
@ -1102,7 +1102,7 @@ generated the application. Without this file, the confirmation dialog box wouldn
![Confirm Dialog](images/getting_started/confirm_dialog.png)
Congratulations, you can now create, show, list, update and destroy
posts.
posts.
TIP: In general, Rails encourages the use of resources objects in place
of declaring routes manually.

@ -174,7 +174,7 @@ end
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
```

@ -36,8 +36,8 @@ This file is as follows:
```ruby
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
require 'rails/commands'
```
@ -373,7 +373,7 @@ The `options[:config]` value defaults to `config.ru` which contains this:
```ruby
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
require ::File.expand_path('../config/environment', __FILE__)
run <%= app_const %>
```
@ -388,7 +388,7 @@ app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
The `initialize` method of `Rack::Builder` will take the block here and execute it within an instance of `Rack::Builder`. This is where the majority of the initialization process of Rails happens. The `require` line for `config/environment.rb` in `config.ru` is the first to run:
```ruby
require ::File.expand_path('../config/environment', __FILE__)
require ::File.expand_path('../config/environment', __FILE__)
```
### `config/environment.rb`
@ -546,7 +546,7 @@ def self.run(app, options={})
else
server.register('/', Rack::Handler::Mongrel.new(app))
end
yield server if block_given?
yield server if block_given?
server.run.join
end
```

@ -366,7 +366,15 @@ create_join_table :products, :categories
which creates a `categories_products` table with two columns called
`category_id` and `product_id`. These columns have the option `:null` set to
`false` by default.
`false` by default. This can be overridden by specifying the `:column_options`
option.
```ruby
create_join_table :products, :categories, column_options: {null: true}
```
will create the `product_id` and `category_id` with the `:null` option as
`true`.
You can pass the option `:table_name` with you want to customize the table
name. For example,
@ -377,16 +385,6 @@ create_join_table :products, :categories, table_name: :categorization
will create a `categorization` table.
By default, `create_join_table` will create two columns with no options, but
you can specify these options using the `:column_options` option. For example,
```ruby
create_join_table :products, :categories, column_options: {null: true}
```
will create the `product_id` and `category_id` with the `:null` option as
`true`.
`create_join_table` also accepts a block, which you can use to add indices
(which are not created by default) or additional columns:
@ -448,7 +446,7 @@ definitions:
* `create_table`
* `create_join_table`
* `drop_table` (must supply a block)
* `drop_join_table` (must supply a block)
* `drop_join_table` (must supply a block)
* `remove_timestamps`
* `rename_column`
* `rename_index`
@ -877,7 +875,7 @@ end
# app/models/product.rb
class Product < ActiveRecord::Base
validates :flag, inclusion: { in: [true, false] }
validates :flag, inclusion: { in: [true, false] }
validates :fuzz, presence: true
end
```

@ -91,7 +91,7 @@ Adds a line inside the `Application` class for `config/application.rb`.
If `options[:env]` is specified, the line is appended to the corresponding file in `config/environments`.
```ruby
environment 'config.action_mailer.default_url_options = {host: 'http://yourwebsite.example.com'}, env: 'production'
environment 'config.action_mailer.default_url_options = {host: "http://yourwebsite.example.com"}', env: 'production'
```
A block can be used in place of the `data` argument.

@ -82,7 +82,7 @@ To use `rackup` instead of Rails' `rails server`, you can put the following insi
```ruby
# Rails.root/config.ru
require ::File.expand_path('../config/environment', __FILE__)
require ::File.expand_path('../config/environment', __FILE__)
use Rack::Debugger
use Rack::ContentLength
@ -131,6 +131,7 @@ use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::Cookies
@ -272,6 +273,10 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
* Runs the prepare callbacks before serving the request.
**`ActiveRecord::Migration::CheckPending`**
* Checks pending migrations and raises `ActiveRecord::PendingMigrationError` if any migrations are pending.
**`ActiveRecord::ConnectionAdapters::ConnectionManagement`**
* Cleans active connections after each request, unless the `rack.test` key in the request environment is set to `true`.

@ -36,7 +36,7 @@ the request is dispatched to the `patients` controller's `show` action with `{ i
### Generating Paths and URLs from Code
You can also generate paths and URLs. If the route above is modified to be:
You can also generate paths and URLs. If the route above is modified to be:
```ruby
get '/patients/:id', to: 'patients#show', as: 'patient'
@ -803,7 +803,7 @@ You should put the `root` route at the top of the file, because it is the most p
NOTE: The `root` route only routes `GET` requests to the action.
You can also use root inside namespaces and scopes as well. For example:
You can also use root inside namespaces and scopes as well. For example:
```ruby
namespace :admin do

@ -63,7 +63,7 @@ Those guidelines apply also to guides.
HTML Guides
-----------
Before generating the guides, make sure that you have the latest version of Bundler installed on your system. As of this writing, you must install Bundler 1.3.5 on your device.
Before generating the guides, make sure that you have the latest version of Bundler installed on your system. As of this writing, you must install Bundler 1.3.5 on your device.
To install the latest version of Bundler, simply run the `gem install bundler` command

@ -346,13 +346,13 @@ Intranet and administration interfaces are popular attack targets, because they
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.
**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 _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.
**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.

@ -64,7 +64,7 @@ YAML-formatted fixtures are a very human-friendly way to describe your sample da
Here's a sample YAML fixture file:
```yaml
# lo & behold! I am a YAML comment!
# lo & behold! I am a YAML comment!
david:
name: David Heinemeier Hansson
birthday: 1979-10-15
@ -159,7 +159,7 @@ class PostTest < ActiveSupport::TestCase
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.
Any method defined within a class inherited from `MiniTest::Unit::TestCase`
Any method defined within a class inherited from `MiniTest::Unit::TestCase`
(which is the superclass of `ActiveSupport::TestCase`) 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.
Rails adds a `test` method that takes a test name and a block. It generates a normal `MiniTest::Unit` test with method names prefixed with `test_`. So,
@ -396,7 +396,7 @@ Rails adds some custom assertions of its own to the `test/unit` framework:
| `assert_no_difference(expressions, message = nil, &amp;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-299, `:redirect` to indicate 300-399, `:missing` to indicate 404, or `:error` to match the 500-599 range|
| `assert_response(type, message = nil)` | Asserts that the response comes with a specific status code. You can specify `:success` to indicate 200-299, `: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.|
@ -622,11 +622,11 @@ The `assert_select` assertion is quite powerful. For more advanced usage, refer
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_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.|
| Assertion | Purpose |
| --------------------------------------------------------- | ------- |
| `assert_select_email` | Allows you to make assertions on the body of an e-mail. |
| `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`:
@ -767,8 +767,8 @@ 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 commands to help in testing. The table below lists all commands that come along in the default Rakefile when you initiate a Rails project.
| Tasks | Description |
| ------------------------ | ----------- |
| Tasks | Description |
| ----------------------- | ----------- |
| `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake test` as Rails will run all the tests by default|
| `rake test:controllers` | Runs all the controller tests from `test/controllers`|
| `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional`|
@ -778,13 +778,6 @@ You don't need to set up and run your tests by hand on a test-by-test basis. Rai
| `rake test:models` | Runs all the model tests from `test/models`|
| `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit`|
There're also some test commands which you can initiate by running rake tasks:
| 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:recent` | Tests recent changes|
| `rake test:uncommitted` | Runs all the tests which are uncommitted. Supports Subversion and Git|
Brief Note About `MiniTest`
-----------------------------

@ -69,6 +69,10 @@ end
If the action is not being used in a public API and you are free to change the
HTTP method, you can update your route to use `patch` instead of `put`:
`PUT` requests to `/users/:id` in Rails 4 get routed to `update` as they are
today. So, if you have an API that gets real PUT requests it is going to work.
The router also routes `PATCH` requests to `/users/:id` to the `update` action.
```ruby
resources :users do
patch :update_name, on: :member

@ -394,4 +394,4 @@ Here are some helpful links to help you learn even more:
* [jquery-ujs list of external articles](https://github.com/rails/jquery-ujs/wiki/External-articles)
* [Rails 3 Remote Links and Forms: A Definitive Guide](http://www.alfajango.com/blog/rails-3-remote-links-and-forms/)
* [Railscasts: Unobtrusive JavaScript](http://railscasts.com/episodes/205-unobtrusive-javascript)
* [Railscasts: Turbolinks](http://railscasts.com/episodes/390-turbolinks)
* [Railscasts: Turbolinks](http://railscasts.com/episodes/390-turbolinks)