diff options
36 files changed, 334 insertions, 380 deletions
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc index 4d78d6142a..a14a6ba18f 100644 --- a/actionmailer/README.rdoc +++ b/actionmailer/README.rdoc @@ -67,12 +67,12 @@ simply call the method and optionally call +deliver+ on the return value. Calling the method returns a Mail Message object: - message = Notifier.welcome # => Returns a Mail::Message object - message.deliver # => delivers the email + message = Notifier.welcome("david@loudthinking.com") # => Returns a Mail::Message object + message.deliver # => delivers the email Or you can just chain the methods together like: - Notifier.welcome.deliver # Creates the email and sends it immediately + Notifier.welcome("david@loudthinking.com").deliver # Creates the email and sends it immediately == Setting defaults @@ -119,8 +119,7 @@ trivial case like this: rails runner 'Mailman.receive(STDIN.read)' However, invoking Rails in the runner for each mail to be received is very resource intensive. A single -instance of Rails should be run within a daemon, if it is going to be utilized to process more than just -a limited number of email. +instance of Rails should be run within a daemon, if it is going to process more than just a limited amount of email. == Configuration diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index ff74185e37..1fff958ceb 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -334,8 +334,8 @@ module ActionMailer # and starts to use it. # * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is # really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name - # of an OpenSSL verify constant ('none', 'peer', 'client_once','fail_if_no_peer_cert') or directly the - # constant (OpenSSL::SSL::VERIFY_NONE, OpenSSL::SSL::VERIFY_PEER,...). + # of an OpenSSL verify constant ('none', 'peer', 'client_once', 'fail_if_no_peer_cert') or directly the + # constant (OpenSSL::SSL::VERIFY_NONE, OpenSSL::SSL::VERIFY_PEER, ...). # # * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method. # * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>. @@ -596,9 +596,9 @@ module ActionMailer # class method: # # class Notifier < ActionMailer::Base - # self.default from: 'no-reply@test.lindsaar.net', - # bcc: 'email_logger@test.lindsaar.net', - # reply_to: 'bounces@test.lindsaar.net' + # default from: 'no-reply@test.lindsaar.net', + # bcc: 'email_logger@test.lindsaar.net', + # reply_to: 'bounces@test.lindsaar.net' # end # # If you need other headers not listed above, you can either pass them in diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 8abd5d6e9c..c10566a87d 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -81,7 +81,7 @@ module ActionView # ==== Options # * <tt>:multiple</tt> - If set to true the selection will allow multiple choices. # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. - # * <tt>:include_blank</tt> - If set to true, an empty option will be create + # * <tt>:include_blank</tt> - If set to true, an empty option will be created. # * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something # * Any other key creates standard HTML attributes for the tag. # diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 44323ce9db..b0bd78ad46 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -17,7 +17,8 @@ module ActiveRecord # be destroyed directly. They will however still be marked for destruction. # # Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>. - # When the <tt>:autosave</tt> option is not present new associations are saved. + # When the <tt>:autosave</tt> option is not present then new association records are + # saved but the updated association records are not saved. # # == Validation # diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 178db07ca1..a8905ed739 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -99,6 +99,9 @@ module ActiveRecord # <tt>before_*</tt> callbacks return +false+ the action is cancelled and # +save+ returns +false+. See ActiveRecord::Callbacks for further # details. + # + # Attributes marked as readonly are silently ignored if the record is + # being updated. def save(*) create_or_update rescue ActiveRecord::RecordInvalid @@ -118,6 +121,9 @@ module ActiveRecord # the <tt>before_*</tt> callbacks return +false+ the action is cancelled # and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See # ActiveRecord::Callbacks for further details. + # + # Attributes marked as readonly are silently ignored if the record is + # being updated. def save!(*) create_or_update || raise(RecordNotSaved) end @@ -204,6 +210,8 @@ module ActiveRecord # * updated_at/updated_on column is updated if that column is available. # * Updates all the attributes that are dirty in this object. # + # This method raises an +ActiveRecord::ActiveRecordError+ if the + # attribute is marked as readonly. def update_attribute(name, value) name = name.to_s verify_readonly_attribute(name) diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb index 7f1972ccf9..744780d069 100644 --- a/activerecord/lib/active_record/validations/associated.rb +++ b/activerecord/lib/active_record/validations/associated.rb @@ -9,8 +9,8 @@ module ActiveRecord end module ClassMethods - # Validates whether the associated object or objects are all valid - # themselves. Works with any kind of association. + # Validates whether the associated object or objects are all valid. + # Works with any kind of association. # # class Book < ActiveRecord::Base # has_many :pages diff --git a/activesupport/lib/active_support/core_ext/array/wrap.rb b/activesupport/lib/active_support/core_ext/array/wrap.rb index 1245768870..152eb02218 100644 --- a/activesupport/lib/active_support/core_ext/array/wrap.rb +++ b/activesupport/lib/active_support/core_ext/array/wrap.rb @@ -15,12 +15,12 @@ class Array # # * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> # moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns - # such a +nil+ right away. + # +nil+ right away. # * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> # raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value. - # * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array. + # * It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+. # - # The last point is particularly worth comparing for some enumerables: + # The second point is easily explained with some enumerables: # # Array(foo: :bar) # => [[:foo, :bar]] # Array.wrap(foo: :bar) # => [{:foo=>:bar}] @@ -29,10 +29,10 @@ class Array # # [*object] # - # which for +nil+ returns <tt>[]</tt>, and calls to <tt>Array(object)</tt> otherwise. + # which returns <tt>[]</tt> for +nil+, but calls to <tt>Array(object)</tt> otherwise. # - # Thus, in this case the behavior may be different for +nil+, and the differences with - # <tt>Kernel#Array</tt> explained above apply to the rest of <tt>object</tt>s. + # The differences with <tt>Kernel#Array</tt> explained above + # apply to the rest of <tt>object</tt>s. def self.wrap(object) if object.nil? [] diff --git a/guides/assets/images/challenge.png b/guides/assets/images/getting_started/challenge.png Binary files differindex 30be3d7028..30be3d7028 100644 --- a/guides/assets/images/challenge.png +++ b/guides/assets/images/getting_started/challenge.png diff --git a/guides/assets/images/getting_started/rails_welcome.png b/guides/assets/images/getting_started/rails_welcome.png Binary files differnew file mode 100644 index 0000000000..569dd846a8 --- /dev/null +++ b/guides/assets/images/getting_started/rails_welcome.png diff --git a/guides/assets/images/rails_welcome.png b/guides/assets/images/rails_welcome.png Binary files differdeleted file mode 100644 index 8ad2d351de..0000000000 --- a/guides/assets/images/rails_welcome.png +++ /dev/null diff --git a/guides/bug_report_templates/active_record_gem.rb b/guides/bug_report_templates/active_record_gem.rb index 2c63342572..2e604bec47 100644 --- a/guides/bug_report_templates/active_record_gem.rb +++ b/guides/bug_report_templates/active_record_gem.rb @@ -1,5 +1,5 @@ # Activate the gem you are reporting the issue against. -gem 'activerecord', '3.2.11' +gem 'activerecord', '3.2.13' require 'active_record' require 'minitest/autorun' require 'logger' diff --git a/guides/source/2_2_release_notes.md b/guides/source/2_2_release_notes.md index 802455f612..7db4cf07e7 100644 --- a/guides/source/2_2_release_notes.md +++ b/guides/source/2_2_release_notes.md @@ -200,7 +200,7 @@ Active Record association proxies now respect the scope of methods on the proxie * More information: * [Rails 2.2 Change: Private Methods on Association Proxies are Private](http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/) -### Other ActiveRecord Changes +### Other Active Record Changes * `rake db:migrate:redo` now accepts an optional VERSION to target that specific migration to redo * Set `config.active_record.timestamped_migrations = false` to have migrations with numeric prefix instead of UTC timestamp. diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md index 7aef566e40..3c08f148cf 100644 --- a/guides/source/2_3_release_notes.md +++ b/guides/source/2_3_release_notes.md @@ -134,7 +134,7 @@ Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, ### Batch Processing -You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using `find_in_batches`: +You can now process large numbers of records from an Active Record model with less pressure on memory by using `find_in_batches`: ```ruby Customer.find_in_batches(:conditions => {:active => true}) do |customer_group| @@ -504,7 +504,7 @@ A lot of folks have adopted the notion of using try() to attempt operations on o ### Swappable Parsers for XMLmini -The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed: +The support for XML parsing in Active Support has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed: ```ruby XmlMini.backend = 'LibXML' diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index 388ba3fa30..ebe8847168 100644 --- a/guides/source/3_0_release_notes.md +++ b/guides/source/3_0_release_notes.md @@ -79,7 +79,7 @@ Creating a Rails 3.0 application -------------------------------- ```bash -# You should have the 'rails' rubygem installed +# You should have the 'rails' RubyGem installed $ rails new myapp $ cd myapp ``` @@ -475,7 +475,7 @@ As well as the following deprecations: * `named_scope` in an Active Record class is deprecated and has been renamed to just `scope`. * In `scope` methods, you should move to using the relation methods, instead of a `:conditions => {}` finder method, for example `scope :since, lambda {|time| where("created_at > ?", time) }`. * `save(false)` is deprecated, in favor of `save(:validate => false)`. -* I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to `:en.errors.template`. +* I18n error messages for Active Record should be changed from :en.activerecord.errors.template to `:en.errors.template`. * `model.errors.on` is deprecated in favor of `model.errors[]` * validates_presence_of => validates... :presence => true * `ActiveRecord::Base.colorize_logging` and `config.active_record.colorize_logging` are deprecated in favor of `Rails::LogSubscriber.colorize_logging` or `config.colorize_logging` @@ -580,7 +580,7 @@ Action Mailer has been given a new API with TMail being replaced out with the ne * All mailers are now in `app/mailers` by default. * Can now send email using new API with three methods: `attachments`, `headers` and `mail`. -* ActionMailer now has native support for inline attachments using the `attachments.inline` method. +* Action Mailer now has native support for inline attachments using the `attachments.inline` method. * Action Mailer emailing methods now return `Mail::Message` objects, which can then be sent the `deliver` message to send itself. * All delivery methods are now abstracted out to the Mail gem. * The mail delivery method can accept a hash of all valid mail header fields with their value pair. diff --git a/guides/source/3_1_release_notes.md b/guides/source/3_1_release_notes.md index d3f8abe0c8..5c99892e39 100644 --- a/guides/source/3_1_release_notes.md +++ b/guides/source/3_1_release_notes.md @@ -137,7 +137,7 @@ Creating a Rails 3.1 application -------------------------------- ```bash -# You should have the 'rails' rubygem installed +# You should have the 'rails' RubyGem installed $ rails new myapp $ cd myapp ``` diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md index 68a47be14f..e036860de2 100644 --- a/guides/source/3_2_release_notes.md +++ b/guides/source/3_2_release_notes.md @@ -67,7 +67,7 @@ Creating a Rails 3.2 application -------------------------------- ```bash -# You should have the 'rails' rubygem installed +# You should have the 'rails' RubyGem installed $ rails new myapp $ cd myapp ``` @@ -101,7 +101,7 @@ Rails 3.2 comes with a development mode that's noticeably faster. Inspired by [A ### Automatic Query Explains -Rails 3.2 comes with a nice feature that explains queries generated by ARel by defining an `explain` method in `ActiveRecord::Relation`. For example, you can run something like `puts Person.active.limit(5).explain` and the query ARel produces is explained. This allows to check for the proper indexes and further optimizations. +Rails 3.2 comes with a nice feature that explains queries generated by Arel by defining an `explain` method in `ActiveRecord::Relation`. For example, you can run something like `puts Person.active.limit(5).explain` and the query Arel produces is explained. This allows to check for the proper indexes and further optimizations. Queries that take more than half a second to run are *automatically* explained in the development mode. This threshold, of course, can be changed. @@ -189,7 +189,7 @@ Action Pack * form\_for is changed to use "#{action}\_#{as}" as the css class and id if `:as` option is provided. Earlier versions used "#{as}\_#{action}". -* `ActionController::ParamsWrapper` on ActiveRecord models now only wrap `attr_accessible` attributes if they were set. If not, only the attributes returned by the class method `attribute_names` will be wrapped. This fixes the wrapping of nested attributes by adding them to `attr_accessible`. +* `ActionController::ParamsWrapper` on Active Record models now only wrap `attr_accessible` attributes if they were set. If not, only the attributes returned by the class method `attribute_names` will be wrapped. This fixes the wrapping of nested attributes by adding them to `attr_accessible`. * Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts. diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 2793d9025f..50a3c6fabc 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -22,7 +22,7 @@ Creating a Rails 4.0 application -------------------------------- ``` - You should have the 'rails' rubygem installed + You should have the 'rails' RubyGem installed $ rails new myapp $ cd myapp ``` @@ -113,7 +113,8 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ * 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 ActionPack out of box. +* Added `ActiveModel::Model`, a mixin to make Ruby objects work with + Action Pack out of box. ### Deprecations @@ -142,7 +143,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ * 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 stdlib. +* 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?` diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index db91425c76..43a59e8d43 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -148,7 +148,7 @@ Also, if you've turned on `config.wrap_parameters` in your initializer or callin And assume that you're sending the data to `CompaniesController`, it would then be wrapped in `:company` key like this: ```ruby -{ :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" } } +{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } } ``` You can customize the name of the key or specific parameters you want to wrap by consulting the [API documentation](http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html) @@ -246,7 +246,7 @@ To declare that the value in `params` must be an array of permitted scalar values map the key to an empty array: ```ruby -params.permit(:id => []) +params.permit(id: []) ``` To whitelist an entire hash of parameters, the `permit!` method can be @@ -266,9 +266,9 @@ mass-assigned. You can also use permit on nested parameters, like: ```ruby -params.permit(:name, {:emails => []}, - :friends => [ :name, - { :family => [ :name ], :hobbies => [] }]) +params.permit(:name, { emails: [] }, + friends: [ :name, + { family: [ :name ], hobbies: [] }]) ``` This declaration whitelists the `name`, `emails` and `friends` diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index ec7b8d4e17..c351339117 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -1,7 +1,7 @@ Action Mailer Basics ==================== -This guide should provide you with all you need to get started in sending and +This guide provides you with all you need to get started in sending and receiving emails from and to your application, and many internals of Action Mailer. It also covers how to test your mailers. diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 2589accadd..80eec428c1 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -707,7 +707,7 @@ Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all You can additionally unscope specific where clauses. For example: ```ruby -Post.where(:id => 10).limit(1).unscope(:where => :id, :limit).order('id DESC') = Post.order('id DESC') +Post.where(:id => 10).limit(1).unscope(where: :id, :limit).order('id DESC') = Post.order('id DESC') ``` ### `only` @@ -1301,6 +1301,11 @@ Client.unscoped { Dynamic Finders --------------- +NOTE: Dynamic finders have been deprecated in Rails 4.0 and will be +removed in Rails 4.1. The best practice is to use Active Record scopes +instead. You can find the deprecation gem at +https://github.com/rails/activerecord-deprecated_finders + For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called `first_name` on your `Client` model for example, you get `find_by_first_name` for free from Active Record. If you have a `locked` field on the `Client` model, you also get `find_by_locked` and methods. You can specify an exclamation point (`!`) on the end of the dynamic finders to get them to raise an `ActiveRecord::RecordNotFound` error if they do not return any records, like `Client.find_by_name!("Ryan")` diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index df39d3c5dc..dfc951f10e 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -434,7 +434,7 @@ end Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when `:minimum` is 1 you should -provide a personalized message or use `validates_presence_of` instead. When +provide a personalized message or use `presence: true` instead. When `:in` or `:within` have a lower limit of 1, you should either provide a personalized message or call `presence` prior to `length`. @@ -768,6 +768,7 @@ class Person < ActiveRecord::Base validates :name, presence: true, on: :save end ``` +The last line is in review state and as of now, it is not running in any version of Rails 3.2.x as discussed in this [issue](https://github.com/rails/rails/issues/10248) Strict Validations ------------------ diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 101a4f5b42..54f4b79b3b 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -10,7 +10,7 @@ After reading this guide, you will know: * What Core Extensions are. * How to load all extensions. * How to cherry-pick just the extensions you want. -* What extensions ActiveSupport provides. +* What extensions Active Support provides. -------------------------------------------------------------------------------- @@ -2216,7 +2216,9 @@ NOTE: Defined in `active_support/core_ext/array/conversions.rb`. The method `to_formatted_s` acts like `to_s` by default. -If the array contains items that respond to `id`, however, it may be passed the symbol `:db` as argument. That's typically used with collections of ARs. Returned strings are: +If the array contains items that respond to `id`, however, the symbol +`:db` may be passed as argument. That's typically used with +collections of Active Record objects. Returned strings are: ```ruby [].to_formatted_s(:db) # => "null" @@ -2372,7 +2374,8 @@ NOTE: Defined in `active_support/core_ext/array/wrap.rb`. ### Duplicating -The method `Array.deep_dup` duplicates itself and all objects inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside. +The method `Array.deep_dup` duplicates itself and all objects inside +recursively with Active Support method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside. ```ruby array = [1, [2, 3]] @@ -2593,7 +2596,8 @@ NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`. ### Deep duplicating -The method `Hash.deep_dup` duplicates itself and all keys and values inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside. +The method `Hash.deep_dup` duplicates itself and all keys and values +inside recursively with Active Support method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside. ```ruby hash = { a: 1, b: { c: 2, d: [3, 4] } } diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index bc4b49dd38..a2849dd98f 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -75,7 +75,7 @@ The query string strategy has several disadvantages: 2. **The file name can change between nodes in multi-server environments.**<br /> The default query string in Rails 2.x is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request. 3. **Too much cache invalidation**<br /> - When static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. + When static assets are deployed with each new release of code, the mtime(time of last modification) of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. Fingerprinting fixes these problems by avoiding query strings, and by ensuring that filenames are consistent based on their content. @@ -450,7 +450,7 @@ The default matcher for compiling files includes `application.js`, `application. NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and `.scss` files are **not** automatically included as they compile to JS/CSS. -If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the `precompile` array: +If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the `precompile` array in `config/application.rb`: ```ruby config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] @@ -459,7 +459,7 @@ config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] Or you can opt to precompile all assets with something like this: ```ruby -# config/environments/production.rb +# config/application.rb config.assets.precompile << Proc.new do |path| if path =~ /\.(css|js)\z/ full_path = Rails.application.assets.resolve(path).to_path @@ -707,7 +707,7 @@ config.assets.cache_store = :memory_store The options accepted by the assets cache store are the same as the application's cache store. ```ruby -config.assets.cache_store = :memory_store, { :size => 32.megabytes } +config.assets.cache_store = :memory_store, { size: 32.megabytes } ``` Adding Assets to Your Gems diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index e1fc3d0f53..456abaf612 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -30,13 +30,13 @@ config.action_controller.perform_caching = true Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with. -INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching) +INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching). See [DHH's key-based cache expiration overview](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method. ### Action Caching Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy. -INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching) +INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching). See [DHH's key-based cache expiration overview](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method. ### Fragment Caching diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 7b7f5963fd..e0b44bbf93 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -201,7 +201,7 @@ Usage: ... -ActiveRecord options: +Active Record options: [--migration] # Indicates when to generate migration # Default: true diff --git a/guides/source/configuring.md b/guides/source/configuring.md index a0ab707b51..9ab6449729 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -58,19 +58,19 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of `config.action_controller.asset_host`. -* `config.autoload_once_paths` accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if `config.cache_classes` is false, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array. +* `config.autoload_once_paths` accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if `config.cache_classes` is `false`, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array. * `config.autoload_paths` accepts an array of paths from which Rails will autoload constants. Default is all directories under `app`. -* `config.cache_classes` controls whether or not application classes and modules should be reloaded on each request. Defaults to false in development mode, and true in test and production modes. Can also be enabled with `threadsafe!`. +* `config.cache_classes` controls whether or not application classes and modules should be reloaded on each request. Defaults to `false` in development mode, and `true` in test and production modes. Can also be enabled with `threadsafe!`. * `config.action_view.cache_template_loading` controls whether or not templates should be reloaded on each request. Defaults to whatever is set for `config.cache_classes`. * `config.cache_store` configures which cache store to use for Rails caching. Options include one of the symbols `:memory_store`, `:file_store`, `:mem_cache_store`, `:null_store`, or an object that implements the cache API. Defaults to `:file_store` if the directory `tmp/cache` exists, and to `:memory_store` otherwise. -* `config.colorize_logging` specifies whether or not to use ANSI color codes when logging information. Defaults to true. +* `config.colorize_logging` specifies whether or not to use ANSI color codes when logging information. Defaults to `true`. -* `config.consider_all_requests_local` is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the `Rails::Info` controller will show the application runtime context in `/rails/info/properties`. True by default in development and test environments, and false in production mode. For finer-grained control, set this to false and implement `local_request?` in controllers to specify which requests should provide debugging information on errors. +* `config.consider_all_requests_local` is a flag. If `true` then any error will cause detailed debugging information to be dumped in the HTTP response, and the `Rails::Info` controller will show the application runtime context in `/rails/info/properties`. `true` by default in development and test environments, and `false` in production mode. For finer-grained control, set this to `false` and implement `local_request?` in controllers to specify which requests should provide debugging information on errors. * `config.console` allows you to set class that will be used as console you run `rails console`. It's best to run it in `console` block: @@ -83,11 +83,11 @@ These configuration methods are to be called on a `Rails::Railtie` object, such end ``` -* `config.dependency_loading` is a flag that allows you to disable constant autoloading setting it to false. It only has effect if `config.cache_classes` is true, which it is by default in production mode. This flag is set to false by `config.threadsafe!`. +* `config.dependency_loading` is a flag that allows you to disable constant autoloading setting it to `false`. It only has effect if `config.cache_classes` is true, which it is by default in production mode. This flag is set to `false` by `config.threadsafe!`. -* `config.eager_load` when true, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks and any other registered namespace. +* `config.eager_load` when `true`, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks and any other registered namespace. -* `config.eager_load_namespaces` registers namespaces that are eager loaded when `config.eager_load` is true. All namespaces in the list must respond to the `eager_load!` method. +* `config.eager_load_namespaces` registers namespaces that are eager loaded when `config.eager_load` is `true`. All namespaces in the list must respond to the `eager_load!` method. * `config.eager_load_paths` accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the `app` directory of the application. @@ -95,7 +95,7 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.exceptions_app` sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`. -* `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.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. @@ -109,11 +109,11 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.middleware` allows you to configure the application's middleware. This is covered in depth in the [Configuring Middleware](#configuring-middleware) section below. -* `config.reload_classes_only_on_change` enables or disables reloading of classes only when tracked files change. By default tracks everything on autoload paths and is set to true. If `config.cache_classes` is true, this option is ignored. +* `config.reload_classes_only_on_change` enables or disables reloading of classes only when tracked files change. By default tracks everything on autoload paths and is set to `true`. If `config.cache_classes` is `true`, this option is ignored. * `config.secret_key_base` used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `config.secret_key_base` initialized to a random key in `config/initializers/secret_token.rb`. -* `config.serve_static_assets` configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. +* `config.serve_static_assets` configures Rails itself to serve static assets. Defaults to `true`, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to `true` when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. * `config.session_store` is usually set up in `config/initializers/session_store.rb` and specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Custom session stores can also be specified: @@ -127,13 +127,13 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.beginning_of_week` sets the default beginning of week for the application. Accepts a valid week day symbol (e.g. `:monday`). -* `config.whiny_nils` enables or disables warnings when a certain set of methods are invoked on `nil` and it does not respond to them. Defaults to true in development and test environments. +* `config.whiny_nils` enables or disables warnings when a certain set of methods are invoked on `nil` and it does not respond to them. Defaults to `true` in development and test environments. ### 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.compress` a flag that enables the compression of compiled assets. It is explicitly set to true in `config/production.rb`. +* `config.assets.compress` a flag that enables the compression of compiled assets. It is explicitly set to `true` in `config/production.rb`. * `config.assets.css_compressor` defines the CSS compressor to use. It is set by default by `sass-rails`. The unique alternative value at the moment is `:yui`, which uses the `yui-compressor` gem. @@ -155,7 +155,7 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.assets.compile` is a boolean that can be used to turn on live Sprockets compilation in production. -* `config.assets.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to the same configured at `config.logger`. Setting `config.assets.logger` to false will turn off served assets logging. +* `config.assets.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to the same configured at `config.logger`. Setting `config.assets.logger` to `false` will turn off served assets logging. ### Configuring Generators @@ -258,21 +258,21 @@ config.middleware.delete "Rack::MethodOverride" * `config.active_record.table_name_suffix` lets you set a global string to be appended to table names. If you set this to `_northwest`, then the Customer class will look for `customers_northwest` as its table. The default is an empty string. -* `config.active_record.pluralize_table_names` specifies whether Rails will look for singular or plural table names in the database. If set to true (the default), then the Customer class will use the `customers` table. If set to false, then the Customer class will use the `customer` table. +* `config.active_record.pluralize_table_names` specifies whether Rails will look for singular or plural table names in the database. If set to `true` (the default), then the Customer class will use the `customers` table. If set to `false`, then the Customer class will use the `customer` table. * `config.active_record.default_timezone` determines whether to use `Time.local` (if set to `:local`) or `Time.utc` (if set to `:utc`) when pulling dates and times from the database. The default is `:utc` for Rails, although Active Record defaults to `:local` when used outside of Rails. * `config.active_record.schema_format` controls the format for dumping the database schema to a file. The options are `:ruby` (the default) for a database-independent version that depends on migrations, or `:sql` for a set of (potentially database-dependent) SQL statements. -* `config.active_record.timestamped_migrations` controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application. +* `config.active_record.timestamped_migrations` controls whether migrations are numbered with serial integers or with timestamps. The default is `true`, to use timestamps, which are preferred if there are multiple developers working on the same application. -* `config.active_record.lock_optimistically` controls whether Active Record will use optimistic locking and is true by default. +* `config.active_record.lock_optimistically` controls whether Active Record will use optimistic locking and is `true` by default. * `config.active_record.cache_timestamp_format` controls the format of the timestamp value in the cache key. Default is `:number`. The MySQL adapter adds one additional configuration option: -* `ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns in a MySQL database to be booleans and is true by default. +* `ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns in a MySQL database to be booleans and is `true` by default. The schema dumper adds one additional configuration option: @@ -284,7 +284,7 @@ The schema dumper adds one additional configuration option: * `config.action_controller.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. -* `config.action_controller.perform_caching` configures whether the application should perform caching or not. Set to false in development mode, true in production. +* `config.action_controller.perform_caching` configures whether the application should perform caching or not. Set to `false` in development mode, `true` in production. * `config.action_controller.default_static_extension` configures the extension used for cached pages. Defaults to `.html`. @@ -342,7 +342,7 @@ The schema dumper adds one additional configuration option: * `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`. See the [ERB documentation](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/) for more information. -* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to false, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authenticity_token => true` as a form option or set this config setting to `true` +* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to `false`, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authenticity_token => true` as a form option or set this config setting to `true` * `config.action_view.prefix_partial_path_with_controller_namespace` determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::PostsController` which renders this template: @@ -370,11 +370,11 @@ There are a number of settings available on `config.action_mailer`: * `:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`. * `:arguments` - The command line arguments. Defaults to `-i -t`. -* `config.action_mailer.raise_delivery_errors` specifies whether to raise an error if email delivery cannot be completed. It defaults to true. +* `config.action_mailer.raise_delivery_errors` specifies whether to raise an error if email delivery cannot be completed. It defaults to `true`. * `config.action_mailer.delivery_method` defines the delivery method. The allowed values are `:smtp` (default), `:sendmail`, and `:test`. -* `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing. +* `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is `true` by default. It can be convenient to set it to `false` for testing. * `config.action_mailer.default_options` configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to: @@ -622,13 +622,13 @@ Below is a comprehensive list of all the initializers found in Rails in the orde * `set_clear_dependencies_hook` Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer — which runs only if `cache_classes` is set to `false` — uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request. -* `initialize_dependency_mechanism` If `config.cache_classes` is true, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them. +* `initialize_dependency_mechanism` If `config.cache_classes` is `true`, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them. * `bootstrap_hook` Runs all configured `before_initialize` blocks. * `i18n.callbacks` In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production mode this callback will only run on the first request. -* `active_support.initialize_whiny_nils` Requires `active_support/whiny_nil` if `config.whiny_nils` is true. This file will output errors such as: +* `active_support.initialize_whiny_nils` Requires `active_support/whiny_nil` if `config.whiny_nils` is `true`. This file will output errors such as: ``` Called id for nil, which would mistakenly be 4 — if you really wanted the id of nil, use object_id @@ -660,7 +660,7 @@ Below is a comprehensive list of all the initializers found in Rails in the orde * `action_controller.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access. -* `active_record.initialize_timezone` Sets `ActiveRecord::Base.time_zone_aware_attributes` to true, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`. +* `active_record.initialize_timezone` Sets `ActiveRecord::Base.time_zone_aware_attributes` to `true`, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`. * `active_record.logger` Sets `ActiveRecord::Base.logger` — if it's not already set — to `Rails.logger`. @@ -708,13 +708,13 @@ Below is a comprehensive list of all the initializers found in Rails in the orde * `build_middleware_stack` Builds the middleware stack for the application, returning an object which has a `call` method which takes a Rack environment object for the request. -* `eager_load!` If `config.eager_load` is true, runs the `config.before_eager_load` hooks and then calls `eager_load!` which will load all `config.eager_load_namespaces`. +* `eager_load!` If `config.eager_load` is `true`, runs the `config.before_eager_load` hooks and then calls `eager_load!` which will load all `config.eager_load_namespaces`. * `finisher_hook` Provides a hook for after the initialization of process of the application is complete, as well as running all the `config.after_initialize` blocks for the application, railties and engines. * `set_routes_reloader` Configures Action Dispatch to reload the routes file using `ActionDispatch::Callbacks.to_prepare`. -* `disable_dependency_loading` Disables the automatic dependency loading if the `config.eager_load` is set to true. +* `disable_dependency_loading` Disables the automatic dependency loading if the `config.eager_load` is set to `true`. Database pooling ---------------- @@ -729,7 +729,7 @@ development: timeout: 5000 ``` -Since the connection pooling is handled inside of ActiveRecord by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. Initially, the database connection pool is empty and it will create additional connections as the demand for them increases, until it reaches the connection pool limit. +Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. Initially, the database connection pool is empty and it will create additional connections as the demand for them increases, until it reaches the connection pool limit. Any one request will check out a connection the first time it requires access to the database, after which it will check the connection back in, at the end of the request, meaning that the additional connection slot will be available again for the next request in the queue. diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 8f1d2922ac..70055c1d7d 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -198,7 +198,9 @@ Adding extra logging like this makes it easy to search for unexpected or unusual ### Tagged Logging -When running multi-user, multi-account applications, it’s often useful to be able to filter the logs using some custom rules. `TaggedLogging` in ActiveSupport helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications. +When running multi-user, multi-account applications, it’s often useful +to be able to filter the logs using some custom rules. `TaggedLogging` +in Active Support helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications. ```ruby logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md index 14ca44d2a1..ef622103f4 100644 --- a/guides/source/development_dependencies_install.md +++ b/guides/source/development_dependencies_install.md @@ -24,7 +24,7 @@ Ruby on Rails uses Git for source code control. The [Git homepage](http://git-sc * [Try Git course](http://try.github.io/) is an interactive course that will teach you the basics. * The [official Documentation](http://git-scm.com/documentation) is pretty comprehensive and also contains some videos with the basics of Git * [Everyday Git](http://schacon.github.io/git/everyday.html) will teach you just enough about Git to get by. -* The [PeepCode screencast](https://peepcode.com/products/git) on Git ($9) is easier to follow. +* The [PeepCode screencast](https://peepcode.com/products/git) on Git is easier to follow. * [GitHub](http://help.github.com) offers links to a variety of Git resources. * [Pro Git](http://git-scm.com/book) is an entire book about Git with a Creative Commons license. diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index d49a30d02f..46115afb8c 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -165,7 +165,7 @@ TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the This will fire up WEBrick, a webserver built into Ruby by default. To see your application in action, open a browser window and navigate to <http://localhost:3000>. You should see the Rails default information page: -![Welcome Aboard screenshot](images/rails_welcome.png) +![Welcome Aboard screenshot](images/getting_started/rails_welcome.png) TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. To verify the server has stopped you should see your command prompt cursor again. For most UNIX-like systems including Mac OS X this will be a dollar sign `$`. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server. @@ -252,29 +252,43 @@ Now that you've seen how to create a controller, an action and a view, let's cre In the Blog application, you will now create a new _resource_. A resource is the term used for a collection of similar objects, such as posts, people or animals. You can create, read, update and destroy items for a resource and these operations are referred to as _CRUD_ operations. -In the next section, you will add the ability to create new posts in your application and be able to view them. This is the "C" and the "R" from CRUD: creation and reading. The form for doing this will look like this: +Rails provides a `resources` method which can be used to declare a +standard REST resource. Here's how `config/routes.rb` will look like. -![The new post form](images/getting_started/new_post.png) +```ruby +Blog::Application.routes.draw do -It will look a little basic for now, but that's ok. We'll look at improving the styling for it afterwards. + resources :posts -### Laying down the ground work + root to: "welcome#index" +end +``` -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`. If you attempt to navigate to that now — by visiting <http://localhost:3000/posts/new> — Rails will give you a routing error: +If you run `rake routes`, you'll see that all the routes for the +standard RESTful actions. -![A routing error, no route matches /posts/new](images/getting_started/routing_error_no_route_matches.png) +```bash +$ rake routes + posts GET /posts(.:format) posts#index + POST /posts(.:format) posts#create + new_post GET /posts/new(.:format) posts#new +edit_post GET /posts/:id/edit(.:format) posts#edit + post GET /posts/:id(.:format) posts#show + PATCH /posts/:id(.:format) posts#update + PUT /posts/:id(.:format) posts#update + DELETE /posts/:id(.:format) posts#destroy + root / welcome#index +``` -This is because there is nowhere inside the routes for the application — defined inside `config/routes.rb` — that defines this route. By default, Rails has no routes configured at all, besides the root route you defined earlier, and so you must define your routes as you need them. +In the next section, you will add the ability to create new posts in your application and be able to view them. This is the "C" and the "R" from CRUD: creation and reading. The form for doing this will look like this: - To do this, you're going to need to create a route inside `config/routes.rb` file, on a new line between the `do` and the `end` for the `draw` method: +![The new post form](images/getting_started/new_post.png) -```ruby -get "posts/new" -``` +It will look a little basic for now, but that's ok. We'll look at improving the styling for it afterwards. -This route is a super-simple route: it defines a new route that only responds to `GET` requests, and that the route is at `posts/new`. But how does it know where to go without the use of the `:to` option? Well, Rails uses a sensible default here: Rails will assume that you want this route to go to the new action inside the posts controller. +### Laying down the ground work -With the route defined, requests can now be made to `/posts/new` in the application. Navigate to <http://localhost:3000/posts/new> and you'll see another 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) @@ -377,14 +391,10 @@ like this is called "create", and so the form should be pointed to that action. Edit the `form_for` line inside `app/views/posts/new.html.erb` to look like this: ```html+erb -<%= form_for :post, url: { action: :create } do |f| %> +<%= form_for :post, url: posts_path do |f| %> ``` -In this example, a `Hash` object is passed to the `:url` option. What Rails will do with this is that it will point the form to the `create` action of the current controller, the `PostsController`, and will send a `POST` request to that route. For this to work, you will need to add a route to `config/routes.rb`, right underneath the one for "posts/new": - -```ruby -post "posts" => "posts#create" -``` +In this example, the `posts_path` helper is passed to the `:url` option. What Rails will do with this is that it will point the form to the `create` action of the current controller, the `PostsController`, and will send a `POST` request to that route. By using the `post` method rather than the `get` method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web. @@ -524,7 +534,7 @@ def create @post = Post.new(params[:post]) @post.save - redirect_to action: :show, id: @post.id + redirect_to @post end ``` @@ -543,16 +553,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. Open `config/routes.rb` and add the following route: +`show` action before proceeding. ```ruby -get "posts/:id" => "posts#show" +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. Note that this -time we had to specify the actual mapping, `posts#show` because -otherwise Rails would not know which action to render. +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. @@ -601,7 +609,7 @@ look like this: @post = Post.new(params[:post].permit(:title, :text)) @post.save - redirect_to action: :show, id: @post.id + redirect_to @post end ``` @@ -613,11 +621,11 @@ 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. As usual, -we'll need a route placed into `config/routes.rb`: +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 -get "posts" => "posts#index" +posts GET /posts(.:format) posts#index ``` And an action for that route inside the `PostsController` in the `app/controllers/posts_controller.rb` file: @@ -669,7 +677,7 @@ for posts. Let's add links to the other views as well, starting with adding this "New Post" link to `app/views/posts/index.html.erb`, placing it above the `<table>` tag: ```erb -<%= link_to 'New post', action: :new %> +<%= link_to 'New post', new_post_path %> ``` This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template — `app/views/posts/new.html.erb` — to go back to the `index` action. Do this by adding this underneath the form in this template: @@ -679,7 +687,7 @@ This link will allow you to bring up the form that lets you create a new post. Y ... <% end %> -<%= link_to 'Back', action: :index %> +<%= link_to 'Back', posts_path %> ``` Finally, add another link to the `app/views/posts/show.html.erb` template to go back to the `index` action as well, so that people who are viewing a single post can go back and view the whole list again: @@ -695,7 +703,7 @@ Finally, add another link to the `app/views/posts/show.html.erb` template to go <%= @post.text %> </p> -<%= link_to 'Back', action: :index %> +<%= link_to 'Back', posts_path %> ``` TIP: If you want to link to an action in the same controller, you don't @@ -755,7 +763,7 @@ def create @post = Post.new(params[:post].permit(:title, :text)) if @post.save - redirect_to action: :show, id: @post.id + redirect_to @post else render 'new' end @@ -776,7 +784,7 @@ something went wrong. To do that, you'll modify `app/views/posts/new.html.erb` to check for error messages: ```html+erb -<%= form_for :post, url: { action: :create } do |f| %> +<%= form_for :post, url: posts_path do |f| %> <% if @post.errors.any? %> <div id="errorExplanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited @@ -803,7 +811,7 @@ something went wrong. To do that, you'll modify </p> <% end %> -<%= link_to 'Back', action: :index %> +<%= link_to 'Back', posts_path %> ``` A few things are going on. We check if there are any errors with @@ -832,14 +840,6 @@ We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating p The first step we'll take is adding an `edit` action to `posts_controller`. -Start by adding a route to `config/routes.rb`: - -```ruby -get "posts/:id/edit" => "posts#edit" -``` - -And then add the controller action: - ```ruby def edit @post = Post.find(params[:id]) @@ -853,7 +853,7 @@ it look as follows: ```html+erb <h1>Editing post</h1> -<%= form_for :post, url: { action: :update, id: @post.id }, +<%= form_for :post, url: post_path(@post.id) }, method: :patch do |f| %> <% if @post.errors.any? %> <div id="errorExplanation"> @@ -881,7 +881,7 @@ method: :patch do |f| %> </p> <% end %> -<%= link_to 'Back', action: :index %> +<%= link_to 'Back', posts_path %> ``` This time we point the form to the `update` action, which is not defined yet @@ -893,21 +893,14 @@ via the `PATCH` HTTP method which is the HTTP method you're expected to use to TIP: By default forms built with the _form_for_ helper are sent via `POST`. -Next, we need to add the `update` action. The file -`config/routes.rb` will need just one more line: - -```ruby -patch "posts/:id" => "posts#update" -``` - -And then create the `update` action in `app/controllers/posts_controller.rb`: +Next we need to create the `update` action in `app/controllers/posts_controller.rb`: ```ruby def update @post = Post.find(params[:id]) if @post.update(params[:post].permit(:title, :text)) - redirect_to action: :show, id: @post.id + redirect_to @post else render 'edit' end @@ -941,8 +934,8 @@ appear next to the "Show" link: <tr> <td><%= post.title %></td> <td><%= post.text %></td> - <td><%= link_to 'Show', action: :show, id: post.id %></td> - <td><%= link_to 'Edit', action: :edit, id: post.id %></td> + <td><%= link_to 'Show', post_path %></td> + <td><%= link_to 'Edit', edit_post_path(post) %></td> </tr> <% end %> </table> @@ -955,8 +948,8 @@ the template: ```html+erb ... -<%= link_to 'Back', action: :index %> -| <%= link_to 'Edit', action: :edit, id: @post.id %> +<%= link_to 'Back', posts_path %> +| <%= link_to 'Edit', edit_post_path(@post) %> ``` And here's how our app looks so far: @@ -1016,7 +1009,7 @@ completely: <%= render 'form' %> -<%= link_to 'Back', action: :index %> +<%= link_to 'Back', posts_path %> ``` Then do the same for the `app/views/posts/edit.html.erb` view: @@ -1026,66 +1019,17 @@ Then do the same for the `app/views/posts/edit.html.erb` view: <%= render 'form' %> -<%= link_to 'Back', action: :index %> +<%= link_to 'Back', posts_path %> ``` -Point your browser to <http://localhost:3000/posts/new> and -try creating a new post. Everything still works. Now try editing the -post and you'll receive the following error: - -![Undefined method post_path](images/getting_started/undefined_method_post_path.png) - -To understand this error, you need to understand how `form_for` works. -When you pass an object to `form_for` and you don't specify a `:url` -option, Rails will try to guess the `action` and `method` options by -checking if the passed object is a new record or not. Rails follows the -REST convention, so to create a new `Post` object it will look for a -route named `posts_path`, and to update a `Post` object it will look for -a route named `post_path` and pass the current object. Similarly, rails -knows that it should create new objects via POST and update them via -PATCH. - -If you run `rake routes` from the console you'll see that we already -have a `posts_path` route, which was created automatically by Rails when we -defined the route for the index action. -However, we don't have a `post_path` yet, which is the reason why we -received an error before. With your server running you can view your routes by visiting [localhost:3000/rails/info/routes](http://localhost:3000/rails/info/routes), or you can generate them from the command line by running `rake routes`: - -```bash -$ rake routes - - posts GET /posts(.:format) posts#index -posts_new GET /posts/new(.:format) posts#new - POST /posts(.:format) posts#create - GET /posts/:id(.:format) posts#show - GET /posts/:id/edit(.:format) posts#edit - PATCH /posts/:id(.:format) posts#update - root / welcome#index -``` - -To fix this, open `config/routes.rb` and modify the `get "posts/:id"` -line like this: - -```ruby -get "posts/:id" => "posts#show", as: :post -``` - -The `:as` option tells the `get` method that we want to make routing helpers -called `post_url` and `post_path` available to our application. These are -precisely the methods that the `form_for` needs when editing a post, and so now -you'll be able to update posts again. - -NOTE: The `:as` option is available on the `post`, `patch`, `put`, `delete` and `match` -routing methods also. - ### Deleting Posts We're now ready to cover the "D" part of CRUD, deleting posts from the -database. Following the REST convention, we're going to add a route for -deleting posts to `config/routes.rb`: +database. Following the REST convention, the route for +deleting posts in the `config/routes.rb` is: ```ruby -delete "posts/:id" => "posts#destroy" +DELETE /posts/:id(.:format) posts#destroy ``` The `delete` routing method should be used for routes that destroy @@ -1105,7 +1049,7 @@ def destroy @post = Post.find(params[:id]) @post.destroy - redirect_to action: :index + redirect_to posts_path end ``` @@ -1132,18 +1076,17 @@ together. <tr> <td><%= post.title %></td> <td><%= post.text %></td> - <td><%= link_to 'Show', action: :show, id: post.id %></td> - <td><%= link_to 'Edit', action: :edit, id: post.id %></td> - <td><%= link_to 'Destroy', { action: :destroy, id: post.id }, + <td><%= link_to 'Show', post_path %></td> + <td><%= link_to 'Edit', edit_post_path(post) %></td> + <td><%= link_to 'Destroy', post_path(post), method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </table> ``` -Here we're using `link_to` in a different way. We wrap the -`:action` and `:id` attributes in a hash so that we can pass those two keys in -first as one argument, and then the final two keys as another argument. The `:method` and `:'data-confirm'` +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`. This is done via the JavaScript file `jquery_ujs` which is automatically included @@ -1153,62 +1096,11 @@ 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. In the next section will see how Rails can aid us when creating -REST applications, and how we can refactor our Blog app to take -advantage of it. - -### Going Deeper into REST - -We've now covered all the CRUD actions of a REST app. We did so by -declaring separate routes with the appropriate verbs into -`config/routes.rb`. Here's how that file looks so far: - -```ruby -get "posts" => "posts#index" -get "posts/new" -post "posts" => "posts#create" -get "posts/:id" => "posts#show", as: :post -get "posts/:id/edit" => "posts#edit" -patch "posts/:id" => "posts#update" -delete "posts/:id" => "posts#destroy" -``` - -That's a lot to type for covering a single **resource**. Fortunately, -Rails provides a `resources` method which can be used to declare a -standard REST resource. Here's how `config/routes.rb` looks after the -cleanup: - -```ruby -Blog::Application.routes.draw do - - resources :posts - - root to: "welcome#index" -end -``` - -If you run `rake routes`, you'll see that all the routes that we -declared before are still available: - -```bash -$ rake routes - posts GET /posts(.:format) posts#index - POST /posts(.:format) posts#create - new_post GET /posts/new(.:format) posts#new -edit_post GET /posts/:id/edit(.:format) posts#edit - post GET /posts/:id(.:format) posts#show - PATCH /posts/:id(.:format) posts#update - PUT /posts/:id(.:format) posts#update - DELETE /posts/:id(.:format) posts#destroy - root / welcome#index -``` - -Also, if you go through the motions of creating, updating and deleting -posts the app still works as before. +posts. TIP: In general, Rails encourages the use of resources objects in place -of declaring routes manually. It was only done in this guide as a learning -exercise. For more information about routing, see +of declaring routes manually. +For more information about routing, see [Rails Routing from the Outside In](routing.html). Adding a Second Model @@ -1722,7 +1614,7 @@ class CommentsController < ApplicationController Now if you try to create a new post, you will be greeted with a basic HTTP Authentication challenge -![Basic HTTP Authentication Challenge](images/challenge.png) +![Basic HTTP Authentication Challenge](images/getting_started/challenge.png) What's Next? ------------ diff --git a/guides/source/i18n.md b/guides/source/i18n.md index d187d3a03a..3c4c1e2cb3 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -258,7 +258,7 @@ match '/:locale' => 'dashboard#index' Do take special care about the **order of your routes**, so this route declaration does not "eat" other ones. (You may want to add it directly before the `root :to` declaration.) -NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's [translate_routes](https://github.com/raul/translate_routes/tree/master). +NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master) and Raul Murciano's [translate_routes](https://github.com/raul/translate_routes/tree/master). ### Setting the Locale from the Client Supplied Information diff --git a/guides/source/initialization.md b/guides/source/initialization.md index 412f2faaaa..72d56b7feb 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -59,35 +59,33 @@ dependencies of the application. `config/boot.rb` sets `ENV['BUNDLE_GEMFILE']` to the location of this file. If the Gemfile exists, `bundler/setup` is then required. -The gems that a Rails 4 application depends on are as follows: - -TODO: change these when the Rails 4 release is near. - -* abstract (1.0.0) -* actionmailer (4.0.0.beta) -* actionpack (4.0.0.beta) -* activemodel (4.0.0.beta) -* activerecord (4.0.0.beta) -* activesupport (4.0.0.beta) -* arel (2.0.7) -* builder (3.0.0) -* bundler (1.0.6) -* erubis (2.6.6) -* i18n (0.5.0) -* mail (2.2.12) -* mime-types (1.16) -* polyglot (0.3.1) -* rack (1.2.1) -* rack-cache (0.5.3) -* rack-mount (0.6.13) -* rack-test (0.5.6) -* rails (4.0.0.beta) -* railties (4.0.0.beta) -* rake (0.8.7) -* sqlite3-ruby (1.3.2) -* thor (0.14.6) -* treetop (1.4.9) -* tzinfo (0.3.23) +A standard Rails application depends on several gems, specifically: + +* abstract +* actionmailer +* actionpack +* activemodel +* activerecord +* activesupport +* arel +* builder +* bundler +* erubis +* i18n +* mail +* mime-types +* polyglot +* rack +* rack-cache +* rack-mount +* rack-test +* rails +* railties +* rake +* sqlite3-ruby +* thor +* treetop +* tzinfo ### `rails/commands.rb` @@ -131,7 +129,7 @@ when 'server' end ``` -This file will change into the root of the directory (a path two directories back from `APP_PATH` which points at `config/application.rb`), but only if the `config.ru` file isn't found. This then requires `rails/commands/server` which sets up the `Rails::Server` class. +This file will change into the Rails root directory (a path two directories up from `APP_PATH` which points at `config/application.rb`), but only if the `config.ru` file isn't found. This then requires `rails/commands/server` which sets up the `Rails::Server` class. ```ruby require 'fileutils' @@ -147,11 +145,11 @@ module Rails ### `actionpack/lib/action_dispatch.rb` Action Dispatch is the routing component of the Rails framework. -It adds functionalities like routing, session, and common middlewares. +It adds functionality like routing, session, and common middlewares. ### `rails/commands/server.rb` -The `Rails::Server` class is defined in this file as inheriting from `Rack::Server`. When `Rails::Server.new` is called, this calls the `initialize` method in `rails/commands/server.rb`: +The `Rails::Server` class is defined in this file by inheriting from `Rack::Server`. When `Rails::Server.new` is called, this calls the `initialize` method in `rails/commands/server.rb`: ```ruby def initialize(*) @@ -441,14 +439,14 @@ inside each of those frameworks, but you're encouraged to try and explore them on your own. For now, just keep in mind that common functionality like Rails engines, -I18n and Rails configuration is all being defined here. +I18n and Rails configuration are all being defined here. ### Back to `config/environment.rb` When `config/application.rb` has finished loading Rails, and defined -your application namespace, you go back to `config/environment.rb`, -where your application is initialized. For example, if you application was called -`Blog`, here you would find `Blog::Application.initialize!`, which is +the application namespace, we go back to `config/environment.rb`, +where the application is initialized. For example, if the application was called +`Blog`, here we would find `Blog::Application.initialize!`, which is defined in `rails/application.rb` ### `railties/lib/rails/application.rb` diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index addc0a5430..1ab841b137 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -1,7 +1,7 @@ Layouts and Rendering in Rails ============================== -This guide covers the basic layout features of Action Controller and Action View. +This guide covers the basic layout features of Action Controller and Action View. After reading this guide, you will know: @@ -283,8 +283,8 @@ Calls to the `render` method generally accept four options: * `:content_type` * `:layout` -* `:status` * `:location` +* `:status` ##### The `:content_type` Option @@ -310,80 +310,86 @@ You can also tell Rails to render with no layout at all: render layout: false ``` -##### The `:status` Option +##### The `:location` Option -Rails will automatically generate a response with the correct HTTP status code (in most cases, this is `200 OK`). You can use the `:status` option to change this: +You can use the `:location` option to set the HTTP `Location` header: ```ruby -render status: 500 -render status: :forbidden +render xml: photo, location: photo_url(photo) ``` -Rails understands both numeric status codes and the corresponding symbols shown below: - -| HTTP Status Code | Symbol | -| ---------------- | -------------------------------- | -| 100 | :continue | -| 101 | :switching_protocols | -| 102 | :processing | -| 200 | :ok | -| 201 | :created | -| 202 | :accepted | -| 203 | :non_authoritative_information | -| 204 | :no_content | -| 205 | :reset_content | -| 206 | :partial_content | -| 207 | :multi_status | -| 226 | :im_used | -| 300 | :multiple_choices | -| 301 | :moved_permanently | -| 302 | :found | -| 303 | :see_other | -| 304 | :not_modified | -| 305 | :use_proxy | -| 306 | :reserved | -| 307 | :temporary_redirect | -| 400 | :bad_request | -| 401 | :unauthorized | -| 402 | :payment_required | -| 403 | :forbidden | -| 404 | :not_found | -| 405 | :method_not_allowed | -| 406 | :not_acceptable | -| 407 | :proxy_authentication_required | -| 408 | :request_timeout | -| 409 | :conflict | -| 410 | :gone | -| 411 | :length_required | -| 412 | :precondition_failed | -| 413 | :request_entity_too_large | -| 414 | :request_uri_too_long | -| 415 | :unsupported_media_type | -| 416 | :requested_range_not_satisfiable | -| 417 | :expectation_failed | -| 418 | :i'm_a_teapot | -| 422 | :unprocessable_entity | -| 423 | :locked | -| 424 | :failed_dependency | -| 426 | :upgrade_required | -| 500 | :internal_server_error | -| 501 | :not_implemented | -| 502 | :bad_gateway | -| 503 | :service_unavailable | -| 504 | :gateway_timeout | -| 505 | :http_version_not_supported | -| 506 | :variant_also_negotiates | -| 507 | :insufficient_storage | -| 510 | :not_extended | - -##### The `:location` Option +##### The `:status` Option -You can use the `:location` option to set the HTTP `Location` header: +Rails will automatically generate a response with the correct HTTP status code (in most cases, this is `200 OK`). You can use the `:status` option to change this: ```ruby -render xml: photo, location: photo_url(photo) +render status: 500 +render status: :forbidden ``` +Rails understands both numeric status codes and the corresponding symbols shown below. + +| Response Class | HTTP Status Code | Symbol | +| ------------------- | ---------------- | -------------------------------- | +| **Informational** | 100 | :continue | +| | 101 | :switching_protocols | +| | 102 | :processing | +| **Success** | 200 | :ok | +| | 201 | :created | +| | 202 | :accepted | +| | 203 | :non_authoritative_information | +| | 204 | :no_content | +| | 205 | :reset_content | +| | 206 | :partial_content | +| | 207 | :multi_status | +| | 208 | :already_reported | +| | 226 | :im_used | +| **Redirection** | 300 | :multiple_choices | +| | 301 | :moved_permanently | +| | 302 | :found | +| | 303 | :see_other | +| | 304 | :not_modified | +| | 305 | :use_proxy | +| | 306 | :reserved | +| | 307 | :temporary_redirect | +| | 308 | :permanent_redirect | +| **Client Error** | 400 | :bad_request | +| | 401 | :unauthorized | +| | 402 | :payment_required | +| | 403 | :forbidden | +| | 404 | :not_found | +| | 405 | :method_not_allowed | +| | 406 | :not_acceptable | +| | 407 | :proxy_authentication_required | +| | 408 | :request_timeout | +| | 409 | :conflict | +| | 410 | :gone | +| | 411 | :length_required | +| | 412 | :precondition_failed | +| | 413 | :request_entity_too_large | +| | 414 | :request_uri_too_long | +| | 415 | :unsupported_media_type | +| | 416 | :requested_range_not_satisfiable | +| | 417 | :expectation_failed | +| | 422 | :unprocessable_entity | +| | 423 | :locked | +| | 424 | :failed_dependency | +| | 426 | :upgrade_required | +| | 423 | :precondition_required | +| | 424 | :too_many_requests | +| | 426 | :request_header_fields_too_large | +| **Server Error** | 500 | :internal_server_error | +| | 501 | :not_implemented | +| | 502 | :bad_gateway | +| | 503 | :service_unavailable | +| | 504 | :gateway_timeout | +| | 505 | :http_version_not_supported | +| | 506 | :variant_also_negotiates | +| | 507 | :insufficient_storage | +| | 508 | :loop_detected | +| | 510 | :not_extended | +| | 511 | :network_authentication_required | + #### Finding Layouts To find the current layout, Rails first looks for a file in `app/views/layouts` with the same base name as the controller. For example, rendering actions from the `PhotosController` class will use `app/views/layouts/photos.html.erb` (or `app/views/layouts/photos.builder`). If there is no such controller-specific layout, Rails will use `app/views/layouts/application.html.erb` or `app/views/layouts/application.builder`. If there is no `.erb` layout, Rails will use a `.builder` layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions. @@ -633,7 +639,7 @@ This would detect that there are no books with the specified ID, populate the `@ ### Using `head` To Build Header-Only Responses -The `head` method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling `render :nothing`. The `head` method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header: +The `head` method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling `render :nothing`. The `head` method accepts a number or symbol (see [reference table](#the-status-option)) representing a HTTP status code. The options argument is interpreted as a hash of header names and values. For example, you can return only an error header: ```ruby head :bad_request @@ -709,7 +715,7 @@ There are three tag options available for the `auto_discovery_link_tag`: * `:rel` specifies the `rel` value in the link. The default value is "alternate". * `:type` specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically. -* `:title` specifies the title of the link. The default value is the uppercased `:type` value, for example, "ATOM" or "RSS". +* `:title` specifies the title of the link. The default value is the uppercase `:type` value, for example, "ATOM" or "RSS". #### Linking to JavaScript Files with the `javascript_include_tag` diff --git a/guides/source/migrations.md b/guides/source/migrations.md index 086cf434d9..9c92efd521 100644 --- a/guides/source/migrations.md +++ b/guides/source/migrations.md @@ -150,7 +150,25 @@ class AddPartNumberToProducts < ActiveRecord::Migration end ``` -Similarly, +If you'd like to add an index on the new column, you can do that as well: + +```bash +$ rails generate migration AddPartNumberToProducts part_number:string:index +``` + +will generate + +```ruby +class AddPartNumberToProducts < ActiveRecord::Migration + def change + add_column :products, :part_number, :string + add_index :products, :part_number + end +end +``` + + +Similarly, you can generate a migration to remove a column from the command line: ```bash $ rails generate migration RemovePartNumberFromProducts part_number:string diff --git a/guides/source/ruby_on_rails_guides_guidelines.md b/guides/source/ruby_on_rails_guides_guidelines.md index 136dfb4cae..d5d1ee0a38 100644 --- a/guides/source/ruby_on_rails_guides_guidelines.md +++ b/guides/source/ruby_on_rails_guides_guidelines.md @@ -63,6 +63,10 @@ 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. + +To install the latest version of Bundler, simply run the `gem install bundler` command + ### Generation To generate all the guides, just `cd` into the `guides` directory, run `bundle install` and execute: diff --git a/guides/source/testing.md b/guides/source/testing.md index 4c0a61bc5e..b02d0b663c 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -85,8 +85,8 @@ ERB allows you to embed Ruby code within templates. The YAML fixture format is p ```erb <% 1000.times do |n| %> user_<%= n %>: - username: <%= "user%03d" % n %> - email: <%= "user%03d@example.com" % n %> + username: <%= "user#{n}" %> + email: <%= "user#{n}@example.com" %> <% end %> ``` @@ -159,9 +159,10 @@ 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 `Test::Unit` test case that begins with `test` (case sensitive) is simply called a test. So, `test_password`, `test_valid_password` and `testValidPassword` all are legal test names and are run automatically when the test case is run. +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 `Test::Unit` test with method names prefixed with `test_`. So, +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, ```ruby test "the truth" do @@ -346,31 +347,38 @@ NOTE: The execution of each test method stops as soon as any error or an asserti Ideally, you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model. -### Assertions Available +### Available Assertions By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned. -There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with `test/unit`, the default testing library used by Rails. The `[msg]` parameter is an optional string message you can specify to make your test failure messages clearer. It's not required. +There are a bunch of different types of assertions you can use. +Here's an extract of the assertions you can use with `minitest`, the default testing library used by Rails. The `[msg]` parameter is an optional string message you can specify to make your test failure messages clearer. It's not required. | Assertion | Purpose | | ---------------------------------------------------------------- | ------- | -| `assert( boolean, [msg] )` | Ensures that the object/expression is true.| +| `assert( test, [msg] )` | Ensures that `test` is true.| +| `refute( test, [msg] )` | Ensures that `test` is false.| | `assert_equal( expected, actual, [msg] )` | Ensures that `expected == actual` is true.| -| `assert_not_equal( expected, actual, [msg] )` | Ensures that `expected != actual` is true.| +| `refute_equal( expected, actual, [msg] )` | Ensures that `expected != actual` is true.| | `assert_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is true.| -| `assert_not_same( expected, actual, [msg] )` | Ensures that `!expected.equal?(actual)` is true.| +| `refute_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is false.| | `assert_nil( obj, [msg] )` | Ensures that `obj.nil?` is true.| -| `assert_not_nil( obj, [msg] )` | Ensures that `!obj.nil?` is true.| +| `refute_nil( obj, [msg] )` | Ensures that `obj.nil?` is false.| | `assert_match( regexp, string, [msg] )` | Ensures that a string matches the regular expression.| -| `assert_no_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.| -| `assert_in_delta( expecting, actual, delta, [msg] )` | Ensures that the numbers `expecting` and `actual` are within `delta` of each other.| +| `refute_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.| +| `assert_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are within `delta` of each other.| +| `refute_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.| | `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.| -| `assert_raise( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.| +| `assert_raises( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.| | `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.| -| `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is of the `class` type.| +| `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is an instance of `class`.| +| `refute_instance_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class`.| | `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is or descends from `class`.| -| `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` has a method called `symbol`.| -| `assert_operator( obj1, operator, obj2, [msg] )` | Ensures that `obj1.operator(obj2)` is true.| +| `refute_kind_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class` and is not descending from it.| +| `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` responds to `symbol`.| +| `refute_respond_to( obj, symbol, [msg] )` | Ensures that `obj` does not respond to `symbol`.| +| `assert_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is true.| +| `refute_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is false.| | `assert_send( array, [msg] )` | Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true. This one is weird eh?| | `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.| @@ -475,7 +483,7 @@ NOTE: Functional tests do not verify whether the specified request type should b ### The Four Hashes of the Apocalypse -After a request has been made by using one of the 5 methods (`get`, `post`, etc.) and processed, you will have 4 Hash objects ready for use: +After a request has been made using one of the 6 methods (`get`, `post`, etc.) and processed, you will have 4 Hash objects ready for use: * `assigns` - Any objects that are stored as instance variables in actions for use in views. * `cookies` - Any cookies that are set. diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb index 89399bcc9f..3dfb724164 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb @@ -39,6 +39,13 @@ Rails.application.routes.draw do # get 'recent', on: :collection # end # end + + # Example resource route with concerns: + # concern :toggleable do + # post 'toggle' + # end + # resources :posts, concerns: :toggleable + # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do |