diff options
Diffstat (limited to 'guides/source')
39 files changed, 541 insertions, 1158 deletions
diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index b4442130ac..dd57787111 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -1,42 +1,24 @@ Ruby on Rails 4.0 Release Notes =============================== -Highlights in Rails 4.0: (WIP) +Highlights in Rails 4.0: * Ruby 1.9.3 only * Strong Parameters * Queue API -* Caching Improvements -* ActionController::Live +* Turbolinks +* Russian Doll Caching +* Asynchronous Mailers -These release notes cover the major changes, but do not include each bug-fix and changes. If you want to see everything, check out the [list of commits](https://github.com/rails/rails/commits/master) in the main Rails repository on GitHub. +These release notes cover only the major changes. To know about various bug fixes and changes, please refer to the change logs or check out the [list of commits](https://github.com/rails/rails/commits/master) in the main Rails repository on GitHub. -------------------------------------------------------------------------------- Upgrading to Rails 4.0 ---------------------- -TODO. This is a WIP guide. +If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 4.0. A list of things to watch out for when upgrading is available in the [Upgrading to Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-3-2-to-rails-4-0) guide. -If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 4.0. Then take heed of the following changes: - -### Rails 4.0 requires at least Ruby 1.9.3 - -Rails 4.0 requires Ruby 1.9.3 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. - -### What to update in your apps - -* Update your Gemfile to depend on - * `rails = 4.0.0` - * `sass-rails ~> 3.2.3` - * `coffee-rails ~> 3.2.1` - * `uglifier >= 1.0.3` - -TODO: Update the versions above. - -* Rails 4.0 removes `vendor/plugins` completely. You have to replace these plugins by extracting them as gems and adding them in your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`. - -TODO: Configuration changes in environment files Creating a Rails 4.0 application -------------------------------- @@ -70,11 +52,14 @@ $ ruby /path/to/rails/railties/bin/rails new myapp --dev Major Features -------------- -Moved to a Plugin ------------------ +TODO. Give a list and then talk about each of them briefly. We can point to relevant code commits or documentation from these sections. + + + +Extraction of features to gems +--------------------------- -With Rails 4 several pieces have been extracted. While Rails won't ship with these features anymore, -you can simply add the extracted plugin to your `Gemfile` to bring the functionality back. +In Rails 4.0, several features have been extracted into gems. You can simply add the extracted gems to your `Gemfile` to bring the functionality back. * Hash-based & Dynamic finder methods ([Github](https://github.com/rails/activerecord-deprecated_finders)) * Mass assignment protection in Active Record models ([Github](https://github.com/rails/protected_attributes), [Pull Request](https://github.com/rails/rails/pull/7251)) @@ -83,6 +68,7 @@ you can simply add the extracted plugin to your `Gemfile` to bring the functiona * Active Resource ([Github](https://github.com/rails/activeresource), [Pull Request](https://github.com/rails/rails/pull/572), [Blog](http://yetimedia.tumblr.com/post/35233051627/activeresource-is-dead-long-live-activeresource)) * Action Caching ([Github](https://github.com/rails/actionpack-action_caching), [Pull Request](https://github.com/rails/rails/pull/7833)) * Page Caching ([Github](https://github.com/rails/actionpack-page_caching), [Pull Request](https://github.com/rails/rails/pull/7833)) +* Sprockets ([Github](https://github.com/rails/sprockets-rails)) Documentation ------------- @@ -94,847 +80,132 @@ Documentation Railties -------- -* Ensure that RAILS_ENV is set when accessing Rails.env. +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes. -* Don't eager-load app/assets and app/views. - -* Add `.rake` to list of file extensions included by `rake notes` and `rake notes:custom`. +### Notable changes * New test locations `test/models`, `test/helpers`, `test/controllers`, and `test/mailers`. Corresponding rake tasks added as well. ([Pull Request](https://github.com/rails/rails/pull/7878)) -* Set a different cache per environment for assets pipeline through `config.assets.cache`. - -* `Rails.public_path` now returns a Pathname object. - -* Remove highly uncommon `config.assets.manifest` option for moving the manifest path. This option is now unsupported in sprockets-rails. - -* Add `config.action_controller.permit_all_parameters` to disable StrongParameters protection, it's false by default. - -* Remove `config.active_record.whitelist_attributes` and `config.active_record.mass_assignment_sanitizer` from new applications since MassAssignmentSecurity has been extracted from Rails. +* Threadsafe on by default -* Change `rails new` and `rails plugin new` generators to name the `.gitkeep` files as `.keep` in a more SCM-agnostic way. Change `--skip-git` option to only skip the `.gitignore` file and still generate the `.keep` files. Add `--skip-keeps` option to skip the `.keep` files. +* Add `Rails.queue` for processing jobs in the background. -* Fixed support for DATABASE_URL environment variable for rake db tasks. - -* rails dbconsole now can use SSL for MySQL. The database.yml options sslca, sslcert, sslcapath, sslcipher and sslkey now affect rails dbconsole. - -* Correctly handle SCRIPT_NAME when generating routes to engine in application that's mounted at a sub-uri. With this behavior, you *should not* use default_url_options[:script_name] to set proper application's mount point by yourself. - -* `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded. +### Deprecations -* The migration generator will now produce AddXXXToYYY/RemoveXXXFromYYY migrations with references statements, for instance +* `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded. - rails g migration AddReferencesToProducts user:references supplier:references{polymorphic} +* `Rails::Plugin` has gone. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies. - will generate the migration with: +Action Mailer +------------- - add_reference :products, :user, index: true - add_reference :products, :supplier, polymorphic: true, index: true +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionmailer/CHANGELOG.md) for detailed changes. -* Allow scaffold/model/migration generators to accept a `polymorphic` modifier for `references`/`belongs_to`, for instance +### Notable changes - ``` - rails g model Product supplier:references{polymorphic} - ``` +* Asynchronously send messages via the Rails Queue. ([Pull Request](https://github.com/rails/rails/pull/6839)) - will generate the model with `belongs_to :supplier, polymorphic: true` association and appropriate migration. +### Deprecations -* Set `config.active_record.migration_error` to `:page_load` for development. +Active Model +------------ -* Add runner to `Rails::Railtie` as a hook called just after runner starts. +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activemodel/CHANGELOG.md) for detailed changes. -* Add `/rails/info/routes` path which displays the same information as `rake routes`. +### Notable changes -* Improved `rake routes` output for redirects. +* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to protect attributes from mass assignment when non-permitted attributes are passed. -* Load all environments available in `config.paths["config/environments"]`. +* Added `ActiveModel::Model`, a mixin to make Ruby objects work with AP out of box. -* Add `config.queue_consumer` to change the job queue consumer from the default `ActiveSupport::ThreadedQueueConsumer`. +### Deprecations -* Add `Rails.queue` for processing jobs in the background. +Active Support +-------------- -* Remove `Rack::SSL` in favour of `ActionDispatch::SSL`. +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activesupport/CHANGELOG.md) for detailed changes. -* Allow to set class that will be used to run as a console, other than IRB, with `Rails.application.config.console=`. It's best to add it to console block. +### Notable changes - ```ruby - # it can be added to config/application.rb - console do - # this block is called only when running console, - # so we can safely require pry here - require "pry" - config.console = Pry - end - ``` +* Replace deprecated `memcache-client` gem with `dalli` in ActiveSupport::Cache::MemCacheStore. -* Add a convenience method `hide!` to Rails generators to hide the current generator namespace from showing when running `rails generate`. +* Optimize ActiveSupport::Cache::Entry to reduce memory and processing overhead. -* Scaffold now uses `content_tag_for` in `index.html.erb`. +* Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument. -* `Rails::Plugin` is removed. Instead of adding plugins to `vendor/plugins`, use gems or bundler with path or git dependencies. +* `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!`. ### Deprecations -Action Mailer -------------- - -* Allow to set default Action Mailer options via `config.action_mailer.default_options=`. +* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from MiniTest instead. -* Raise an `ActionView::MissingTemplate` exception when no implicit template could be found. +* ActiveSupport::Benchmarkable#silence has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1. -* Asynchronously send messages via the Rails Queue. ([Pull Request](https://github.com/rails/rails/pull/6839)) +* `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals. -* Delivery Options (such as SMTP Settings) can now be set dynamically per mailer action. +* Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols). - Delivery options are set via <tt>:delivery_method_options</tt> key on mail. +* BufferedLogger is deprecated. Use ActiveSupport::Logger, or the logger from Ruby stdlib. - ```ruby - def welcome_mailer(user,company) - delivery_options = { user_name: company.smtp_user, password: company.smtp_password, address: company.smtp_host } - mail(to: user.email, subject: "Welcome!", delivery_method_options: delivery_options) - end - ``` - -* Allow for callbacks in mailers similar to ActionController::Base. You can now set up headers/attachments using `before_filter` or `after_filter`. You could also change delivery settings or prevent delivery in an after filter based on instance variables set in your mailer action. You have access to `ActionMailer::Base` instance methods like `message`, `attachments`, `headers`. Action Pack ----------- -### Action Controller - -* Add `ActionController::Flash.add_flash_types` method to allow people to register their own flash types. e.g.: - - ```ruby - class ApplicationController - add_flash_types :error, :warning - end - ``` - - If you add the above code, you can use `<%= error %>` in an erb, and `redirect_to /foo, :error => 'message'` in a controller. - -* Encrypted Cookies + Sign using Derived Keys. ([Pull Request](https://github.com/rails/rails/pull/8112)) - -* Remove Active Model dependency from Action Pack. - -* Support unicode characters in routes. Route will be automatically escaped, so instead of manually escaping: - - ```ruby - get Rack::Utils.escape('こんにちは') => 'home#index' - ``` - - You just have to write the unicode route: - - ```ruby - get 'こんにちは' => 'home#index' - ``` - -* Return proper format on exceptions. - -* Extracted redirect logic from `ActionController::ForceSSL::ClassMethods.force_ssl` into `ActionController::ForceSSL#force_ssl_redirect`. - -* URL path parameters with invalid encoding now raise `ActionController::BadRequest`. - -* Malformed query and request parameter hashes now raise `ActionController::BadRequest`. - -* `respond_to` and `respond_with` now raise `ActionController::UnknownFormat` instead of directly returning head 406. The exception is rescued and converted to 406 in the exception handling middleware. - -* JSONP now uses `application/javascript` instead of `application/json` as the MIME type. - -* Session arguments passed to process calls in functional tests are now merged into the existing session, whereas previously they would replace the existing session. This change may break some existing tests if they are asserting the exact contents of the session but should not break existing tests that only assert individual keys. - -* Forms of persisted records use always PATCH (via the `_method` hack). - -* For resources, both PATCH and PUT are routed to the `update` action. - -* Don't ignore `force_ssl` in development. This is a change of behavior - use an `:if` condition to recreate the old behavior. - - ```ruby - class AccountsController < ApplicationController - force_ssl :if => :ssl_configured? - - def ssl_configured? - !Rails.env.development? - end - end - ``` - -#### Deprecations - -* Deprecated `ActionController::Integration` in favour of `ActionDispatch::Integration`. - -* Deprecated `ActionController::IntegrationTest` in favour of `ActionDispatch::IntegrationTest`. - -* Deprecated `ActionController::PerformanceTest` in favour of `ActionDispatch::PerformanceTest`. - -* Deprecated `ActionController::AbstractRequest` in favour of `ActionDispatch::Request`. - -* Deprecated `ActionController::Request` in favour of `ActionDispatch::Request`. - -* Deprecated `ActionController::AbstractResponse` in favour of `ActionDispatch::Response`. - -* Deprecated `ActionController::Response` in favour of `ActionDispatch::Response`. - -* Deprecated `ActionController::Routing` in favour of `ActionDispatch::Routing`. - -### Action Dispatch - -* Add Routing Concerns to declare common routes that can be reused inside others resources and routes. - - Code before: - - ```ruby - resources :messages do - resources :comments - end - - resources :posts do - resources :comments - resources :images, only: :index - end - ``` - - Code after: - - ```ruby - concern :commentable do - resources :comments - end - - concern :image_attachable do - resources :images, only: :index - end - - resources :messages, concerns: :commentable - - resources :posts, concerns: [:commentable, :image_attachable] - ``` +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes. -* Show routes in exception page while debugging a `RoutingError` in development. +### Notable changes -* Helper methods for HTML5 inputs. ([Pull Request](https://github.com/rails/rails/pull/6359)) - -* Include `mounted_helpers` (helpers for accessing mounted engines) in `ActionDispatch::IntegrationTest` by default. - -* Added `ActionDispatch::SSL` middleware that when included force all the requests to be under HTTPS protocol. - -* Copy literal route constraints to defaults so that url generation know about them. The copied constraints are `:protocol`, `:subdomain`, `:domain`, `:host` and `:port`. - -* Allows `assert_redirected_to` to match against a regular expression. - -* Adds a backtrace to the routing error page in development. - -* `assert_generates`, `assert_recognizes`, and `assert_routing` all raise `Assertion` instead of `RoutingError`. - -* Allows the route helper root to take a string argument. For example, `root 'pages#main'` as a shortcut for `root to: 'pages#main'`. - -* Adds support for the PATCH verb: Request objects respond to `patch?`. Routes now have a new `patch` method, and understand `:patch` in the existing places where a verb is configured, like `:via`. Functional tests have a new method `patch` and integration tests have a new method `patch_via_redirect`. -If `:patch` is the default verb for updates, edits are tunneled as `PATCH` rather than as `PUT` and routing acts accordingly. - -* Integration tests support the OPTIONS method. - -* `expires_in` accepts a `must_revalidate` flag. If true, "must-revalidate" is added to the `Cache-Control` header. - -* Default responder will now always use your overridden block in `respond_with` to render your response. - -* Turn off verbose mode of `rack-cache`, we still have `X-Rack-Cache` to check that info. - -#### Deprecations - -### Action View - -* Remove Active Model dependency from Action Pack. - -* Allow to use `mounted_helpers` (helpers for accessing mounted engines) in `ActionView::TestCase`. - -* Make current object and counter (when it applies) variables accessible when rendering templates with `:object` or `:collection`. - -* Allow to lazy load `default_form_builder` by passing a string instead of a constant. - -* Add index method to `FormBuilder` class. - -* Adds support for layouts when rendering a partial with a given collection. - -* Remove `:disable_with` in favor of `data-disable-with` option from `submit_tag`, `button_tag` and `button_to` helpers. - -* Remove `:mouseover` option from `image_tag` helper. - -* Templates without a handler extension now raises a deprecation warning but still defaults to `ERb`. In future releases, it will simply return the template content. - -* Add a `divider` option to `grouped_options_for_select` to generate a separator optgroup automatically, and deprecate prompt as third argument, in favor of using an options hash. - -* Add `time_field` and `time_field_tag` helpers which render an `input[type="time"]` tag. - -* Removed old `text_helper` apis for `highlight`, `excerpt` and `word_wrap`. - -* Remove the leading \n added by textarea on `assert_select`. - -* Changed default value for `config.action_view.embed_authenticity_token_in_remote_forms` to false. This change breaks remote forms that need to work also without JavaScript, so if you need such behavior, you can either set it to true or explicitly pass `:authenticity_token => true` in form options. - -* Make possible to use a block in `button_to` helper if button text is hard to fit into the name parameter: - - ```ruby - <%= button_to [:make_happy, @user] do %> - Make happy <strong><%= @user.name %></strong> - <% end %> - # => "<form method="post" action="/users/1/make_happy" class="button_to"> - # <div> - # <button type="submit"> - # Make happy <strong>Name</strong> - # </button> - # </div> - # </form>" - ``` - -* Replace `include_seconds` boolean argument with `:include_seconds => true` option in `distance_of_time_in_words` and `time_ago_in_words` signature. - -* Remove `button_to_function` and `link_to_function` helpers. - -* `truncate` now always returns an escaped HTML-safe string. The option `:escape` can be used as `false` to not escape the result. - -* `truncate` now accepts a block to show extra content when the text is truncated. - -* Add `week_field`, `week_field_tag`, `month_field`, `month_field_tag`, `datetime_local_field`, `datetime_local_field_tag`, `datetime_field` and `datetime_field_tag` helpers. - -* Add `color_field` and `color_field_tag` helpers. - -* Add `include_hidden` option to select tag. With `:include_hidden => false` select with multiple attribute doesn't generate hidden input with blank value. - -* Removed default size option from the `text_field`, `search_field`, `telephone_field`, `url_field`, `email_field` helpers. - -* Removed default cols and rows options from the `text_area` helper. - -* Adds `image_url`, `javascript_url`, `stylesheet_url`, `audio_url`, `video_url`, and `font_url` to assets tag helper. These URL helpers will return the full path to your assets. This is useful when you are going to reference this asset from external host. - -* Allow `value_method` and `text_method` arguments from `collection_select` and `options_from_collection_for_select` to receive an object that responds to `:call` such as a proc, to evaluate the option in the current element context. This works the same way with `collection_radio_buttons` and `collection_check_boxes`. - -* Add `date_field` and `date_field_tag` helpers which render an `input[type="date"]` tag. - -* Add `collection_check_boxes` form helper, similar to `collection_select`: - - ```ruby - collection_check_boxes :post, :author_ids, Author.all, :id, :name - # Outputs something like: - <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" /> - <label for="post_author_ids_1">D. Heinemeier Hansson</label> - <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" /> - <label for="post_author_ids_2">D. Thomas</label> - <input name="post[author_ids][]" type="hidden" value="" /> - ``` - - The label/check_box pairs can be customized with a block. - -* Add `collection_radio_buttons` form helper, similar to `collection_select`: - - ```ruby - collection_radio_buttons :post, :author_id, Author.all, :id, :name - # Outputs something like: - <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" /> - <label for="post_author_id_1">D. Heinemeier Hansson</label> - <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" /> - <label for="post_author_id_2">D. Thomas</label> - ``` - - The label/radio_button pairs can be customized with a block. - -* `check_box` with an HTML5 attribute `:form` will now replicate the `:form` attribute to the hidden field as well. - -* label form helper accepts `:for => nil` to not generate the attribute. - -* Add `:format` option to `number_to_percentage`. - -* Add `config.action_view.logger` to configure logger for `Action View`. - -* `check_box` helper with `:disabled => true` will generate a `disabled` hidden field to conform with the HTML convention where disabled fields are not submitted with the form. This is a behavior change, previously the hidden tag had a value of the disabled checkbox. - -* `favicon_link_tag` helper will now use the favicon in `app/assets` by default. - -* `ActionView::Helpers::TextHelper#highlight` now defaults to the HTML5 `mark` element. - -#### Deprecations - -### Sprockets +### Deprecations -Moved into a separate gem `sprockets-rails`. Active Record ------------- -* Add `add_reference` and `remove_reference` schema statements. Aliases, `add_belongs_to` and `remove_belongs_to` are acceptable. References are reversible. - - ```ruby - # Create a user_id column - add_reference(:products, :user) - - # Create a supplier_id, supplier_type columns and appropriate index - add_reference(:products, :supplier, polymorphic: true, index: true) - - # Remove polymorphic reference - remove_reference(:products, :supplier, polymorphic: true) - ``` - -* Add `:default` and `:null` options to `column_exists?`. - - ```ruby - column_exists?(:testings, :taggable_id, :integer, null: false) - column_exists?(:testings, :taggable_type, :string, default: 'Photo') - ``` - -* `ActiveRecord::Relation#inspect` now makes it clear that you are dealing with a `Relation` object rather than an array: - - ```ruby - User.where(:age => 30).inspect - # => <ActiveRecord::Relation [#<User ...>, #<User ...>]> - - User.where(:age => 30).to_a.inspect - # => [#<User ...>, #<User ...>] - ``` - - if more than 10 items are returned by the relation, inspect will only show the first 10 followed by ellipsis. - -* Add `:collation` and `:ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later. - - ```yaml - development: - adapter: postgresql - host: localhost - database: rails_development - username: foo - password: bar - encoding: UTF8 - collation: ja_JP.UTF8 - ctype: ja_JP.UTF8 - ``` - -* `FinderMethods#exists?` now returns `false` with the `false` argument. +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes. -* Added support for specifying the precision of a timestamp in the postgresql adapter. So, instead of having to incorrectly specify the precision using the `:limit` option, you may use `:precision`, as intended. For example, in a migration: +### Notable changes - ```ruby - def change - create_table :foobars do |t| - t.timestamps :precision => 0 - end - end - ``` +* Adds some metadata columns to `schema_migrations` table. -* Allow `ActiveRecord::Relation#pluck` to accept multiple columns. Returns an array of arrays containing the typecasted values: + * `migrated_at` + * `fingerprint` - an md5 hash of the migration. + * `name` - the filename minus version and extension. - ```ruby - Person.pluck(:id, :name) - # SELECT people.id, people.name FROM people - # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']] - ``` +* Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support. -* Improve the derivation of HABTM join table name to take account of nesting. It now takes the table names of the two models, sorts them lexically and then joins them, stripping any common prefix from the second table name. Some examples: +* Add `Relation#load` to explicitly load the record and return `self`. - ``` - Top level models (Category <=> Product) - Old: categories_products - New: categories_products - - Top level models with a global table_name_prefix (Category <=> Product) - Old: site_categories_products - New: site_categories_products - - Nested models in a module without a table_name_prefix method (Admin::Category <=> Admin::Product) - Old: categories_products - New: categories_products - - Nested models in a module with a table_name_prefix method (Admin::Category <=> Admin::Product) - Old: categories_products - New: admin_categories_products - - Nested models in a parent model (Catalog::Category <=> Catalog::Product) - Old: categories_products - New: catalog_categories_products - - Nested models in different parent models (Catalog::Category <=> Content::Page) - Old: categories_pages - New: catalog_categories_content_pages - ``` - -* Move HABTM validity checks to `ActiveRecord::Reflection`. One side effect of this is to move when the exceptions are raised from the point of declaration to when the association is built. This is consistant with other association validity checks. - -* Added `stored_attributes` hash which contains the attributes stored using `ActiveRecord::Store`. This allows you to retrieve the list of attributes you've defined. - - ```ruby - class User < ActiveRecord::Base - store :settings, accessors: [:color, :homepage] - end - - User.stored_attributes[:settings] # [:color, :homepage] - ``` - -* PostgreSQL default log level is now 'warning', to bypass the noisy notice messages. You can change the log level using the `min_messages` option available in your `config/database.yml`. - -* Add uuid datatype support to PostgreSQL adapter. +* `Model.all` now returns an `ActiveRecord::Relation`, rather than an array of records. Use `Relation#to_a` if you really want an array. In some specific cases, this may cause breakage when upgrading. * Added `ActiveRecord::Migration.check_pending!` that raises an error if migrations are pending. -* Added `#destroy!` which acts like `#destroy` but will raise an `ActiveRecord::RecordNotDestroyed` exception instead of returning `false`. - -* Allow blocks for count with `ActiveRecord::Relation`, to work similar as `Array#count`: `Person.where("age > 26").count { |person| person.gender == 'female' }` - -* Added support to `CollectionAssociation#delete` for passing fixnum or string values as record ids. This finds the records responding to the ids and deletes them. - - ```ruby - class Person < ActiveRecord::Base - has_many :pets - end - - person.pets.delete("1") # => [#<Pet id: 1>] - person.pets.delete(2, 3) # => [#<Pet id: 2>, #<Pet id: 3>] - ``` - -* It's not possible anymore to destroy a model marked as read only. - -* Added ability to `ActiveRecord::Relation#from` to accept other `ActiveRecord::Relation` objects. - * Added custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this: - ```ruby - store :settings, accessors: [ :color, :homepage ], coder: JSON - ``` - -* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in `config/database.yml`. ([Pull Request](https://github.com/rails/rails/pull/6069)) - -* Added default order to `ActiveRecord::Base#first` to assure consistent results among different database engines. Introduced `ActiveRecord::Base#take` as a replacement to the old behavior. - -* Added an `:index` option to automatically create indexes for `references` and `belongs_to` statements in migrations. This can be either a boolean or a hash that is identical to options available to the `add_index` method: - - ```ruby - create_table :messages do |t| - t.references :person, :index => true - end - ``` - - Is the same as: - - ```ruby - create_table :messages do |t| - t.references :person - end - add_index :messages, :person_id - ``` - - Generators have also been updated to use the new syntax. - -* Added bang methods for mutating `ActiveRecord::Relation` objects. For example, while `foo.where(:bar)` will return a new object leaving foo unchanged, `foo.where!(:bar)` will mutate the foo object. - -* Added `#find_by` and `#find_by!` to mirror the functionality provided by dynamic finders in a way that allows dynamic input more easily: - - ```ruby - Post.find_by name: 'Spartacus', rating: 4 - Post.find_by "published_at < ?", 2.weeks.ago - Post.find_by! name: 'Spartacus' - ``` - -* Added `ActiveRecord::Base#slice` to return a hash of the given methods with their names as keys and returned values as values. - -* Remove IdentityMap - IdentityMap has never graduated to be an "enabled-by-default" feature, due to some inconsistencies with associations, as described in this [commit](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). Hence the removal from the codebase, until such issues are fixed. - -* Added a feature to dump/load internal state of `SchemaCache` instance because we want to boot more quickly when we have many models. ([Pull Request](https://github.com/rails/rails/pull/5162)) - - ```ruby - # execute rake task. - RAILS_ENV=production bundle exec rake db:schema:cache:dump - => generate db/schema_cache.dump - - # add config.use_schema_cache_dump = true in config/production.rb. BTW, true is default. - - # boot rails. - RAILS_ENV=production bundle exec rails server - => use db/schema_cache.dump - - # If you remove clear dumped cache, execute rake task. - RAILS_ENV=production bundle exec rake db:schema:cache:clear - => remove db/schema_cache.dump - ``` + store :settings, accessors: [ :color, :homepage ], coder: JSON -* Added support for partial indices to `PostgreSQL` adapter. +* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`. -* The `add_index` method now supports a `where` option that receives a string with the partial index criteria. +* Remove IdentityMap. -* Added the `ActiveRecord::NullRelation` class implementing the null object pattern for the Relation class. - -* Implemented `ActiveRecord::Relation#none` method which returns a chainable relation with zero records (an instance of the `NullRelation` class). Any subsequent condition chained to the returned relation will continue generating an empty relation and will not fire any query to the database. +* Adds `ActiveRecord::NullRelation` and `ActiveRecord::Relation#none` implementing the null object pattern for the Relation class. * Added `create_join_table` migration helper to create HABTM join tables. - ```ruby - create_join_table :products, :categories - # => - # create_table :categories_products, :id => false do |td| - # td.integer :product_id, :null => false - # td.integer :category_id, :null => false - # end - ``` - -* The primary key is always initialized in the `@attributes` hash to nil (unless another value has been specified). - -* In previous releases, the following would generate a single query with an OUTER JOIN comments, rather than two separate queries: - - ```ruby - Post.includes(:comments).where("comments.name = 'foo'") - ``` - - This behaviour relies on matching SQL string, which is an inherently flawed idea unless we write an SQL parser, which we do not wish to do. Therefore, it is now deprecated. - - To avoid deprecation warnings and for future compatibility, you must explicitly state which tables you reference, when using SQL snippets: - - ```ruby - Post.includes(:comments).where("comments.name = 'foo'").references(:comments) - ``` - - Note that you do not need to explicitly specify references in the following cases, as they can be automatically inferred: - - ```ruby - Post.where(comments: { name: 'foo' }) - Post.where('comments.name' => 'foo') - Post.order('comments.name') - ``` - - You also do not need to worry about this unless you are doing eager loading. Basically, don't worry unless you see a deprecation warning or (in future releases) an SQL error due to a missing JOIN. - -* Support for the `schema_info` table has been dropped. Please switch to `schema_migrations`. - -* Connections *must* be closed at the end of a thread. If not, your connection pool can fill and an exception will be raised. - -* PostgreSQL hstore records can be created. - -* PostgreSQL hstore types are automatically deserialized from the database. - -* Support for array datatype in PostgreSQL. ([Pull Request](https://github.com/rails/rails/pull/7547)) - -* Added `#update_columns` method which updates the attributes from the passed-in hash without calling save, hence skipping validations and callbacks. `ActiveRecordError` will be raised when called on new objects or when at least one of the attributes is marked as read only. - - ```ruby - post.attributes # => {"id"=>2, "title"=>"My title", "body"=>"My content", "author"=>"Peter"} - post.update_columns({title: 'New title', author: 'Sebastian'}) # => true - post.attributes # => {"id"=>2, "title"=>"New title", "body"=>"My content", "author"=>"Sebastian"} - ``` - -### Deprecations - -* Deprecated most of the 'dynamic finder' methods. All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's how you can rewrite the code: - - ```ruby - find_all_by_... can be rewritten using where(...) - find_last_by_... can be rewritten using where(...).last - scoped_by_... can be rewritten using where(...) - find_or_initialize_by_... can be rewritten using where(...).first_or_initialize - find_or_create_by_... can be rewritten using where(...).first_or_create - find_or_create_by_...! can be rewritten using where(...).first_or_create! - ``` - - The implementation of the deprecated dynamic finders has been moved to the `active_record_deprecated_finders` gem. - -* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do. For example this: - - ```ruby - Post.find(:all, :conditions => { :comments_count => 10 }, :limit => 5) - ``` - - should be rewritten in the new style which has existed since Rails 3: - - ```ruby - Post.where(comments_count: 10).limit(5) - ``` - - Note that as an interim step, it is possible to rewrite the above as: - - ```ruby - Post.scoped(:where => { :comments_count => 10 }, :limit => 5) - ``` - - This could save you a lot of work if there is a lot of old-style finder usage in your application. - - Calling `Post.scoped(options)` is a shortcut for `Post.scoped.merge(options)`. `Relation#merge` now accepts a hash of options, but they must be identical to the names of the equivalent finder method. These are mostly identical to the old-style finder option names, except in the following cases: - - ``` - :conditions becomes :where - :include becomes :includes - :extend becomes :extending - ``` - - The code to implement the deprecated features has been moved out to the `active_record_deprecated_finders` gem. This gem is a dependency of Active Record in Rails 4.0. It will no longer be a dependency from Rails 4.1, but if your app relies on the deprecated features then you can add it to your own Gemfile. It will be maintained by the Rails core team until Rails 5.0 is released. - -* Deprecate eager-evaluated scopes. - - Don't use this: - - ```ruby - scope :red, where(color: 'red') - default_scope where(color: 'red') - ``` - - Use this: - - ```ruby - scope :red, -> { where(color: 'red') } - default_scope { where(color: 'red') } - ``` - - The former has numerous issues. It is a common newbie gotcha to do the following: - - ```ruby - scope :recent, where(published_at: Time.now - 2.weeks) - ``` - - Or a more subtle variant: - - ```ruby - scope :recent, -> { where(published_at: Time.now - 2.weeks) } - scope :recent_red, recent.where(color: 'red') - ``` - - Eager scopes are also very complex to implement within Active Record, and there are still bugs. For example, the following does not do what you expect: - - ```ruby - scope :remove_conditions, except(:where) - where(...).remove_conditions # => still has conditions - ``` - -* Added deprecation for the `:dependent => :restrict` association option. - -* Up until now `has_many` and `has_one, :dependent => :restrict` option raised a `DeleteRestrictionError` at the time of destroying the object. Instead, it will add an error on the model. - -* To fix this warning, make sure your code isn't relying on a `DeleteRestrictionError` and then add `config.active_record.dependent_restrict_raises = false` to your application config. - -* New rails application would be generated with the `config.active_record.dependent_restrict_raises = false` in the application config. - -* The migration generator now creates a join table with (commented) indexes every time the migration name contains the word "join_table". - -* `ActiveRecord::SessionStore` is removed from Rails 4.0 and is now a separate [gem](https://github.com/rails/activerecord-session_store). - -Active Model ------------- - -* Changed `AM::Serializers::JSON.include_root_in_json` default value to false. Now, AM Serializers and AR objects have the same default behaviour. - - ```ruby - class User < ActiveRecord::Base; end - - class Person - include ActiveModel::Model - include ActiveModel::AttributeMethods - include ActiveModel::Serializers::JSON - - attr_accessor :name, :age - - def attributes - instance_values - end - end - - user.as_json - => {"id"=>1, "name"=>"Konata Izumi", "age"=>16, "awesome"=>true} - # root is not included - - person.as_json - => {"name"=>"Francesco", "age"=>22} - # root is not included - ``` - -* Passing false hash values to `validates` will no longer enable the corresponding validators. - -* `ConfirmationValidator` error messages will attach to `:#{attribute}_confirmation` instead of `attribute`. - -* Added `ActiveModel::Model`, a mixin to make Ruby objects work with Action Pack out of the box. ([Pull Request](https://github.com/rails/rails/pull/5253)) - -* `ActiveModel::Errors#to_json` supports a new parameter `:full_messages`. - -* Trims down the API by removing `valid?` and `errors.full_messages`. - -### Deprecations - -Active Resource ---------------- - -* Active Resource is removed from Rails 4.0 and is now a separate [gem](https://github.com/rails/activeresource). - -Active Support --------------- - -* Add default values to all `ActiveSupport::NumberHelper` methods, to avoid errors with empty locales or missing values. - -* `Time#change` now works with time values with offsets other than UTC or the local time zone. - -* Add `Time#prev_quarter` and `Time#next_quarter` short-hands for `months_ago(3)` and `months_since(3)`. - -* Add `Time#last_week`, `Time#last_month`, `Time#last_year` as aliases for `Time#prev_week`, `Time#prev_month`, and `Time#prev_year`. - -* Add `Date#last_week`, `Date#last_month`, `Date#last_year` as aliases for `Date#prev_week`, `Date#prev_month`, and `Date#prev_year`. - -* Remove obsolete and unused `require_association` method from dependencies. - -* Add `:instance_accessor` option for `config_accessor`. - - ```ruby - class User - include ActiveSupport::Configurable - config_accessor :allowed_access, instance_accessor: false - end - - User.new.allowed_access = true # => NoMethodError - User.new.allowed_access # => NoMethodError - ``` - -* `ActionView::Helpers::NumberHelper` methods have been moved to `ActiveSupport::NumberHelper` and are now available via `Numeric#to_s`. - -* `Numeric#to_s` now accepts the formatting options :phone, :currency, :percentage, :delimited, :rounded, :human, and :human_size. - -* Add `Hash#transform_keys`, `Hash#transform_keys!`, `Hash#deep_transform_keys` and `Hash#deep_transform_keys!`. - -* Changed xml type datetime to dateTime (with upper case letter T). - -* Add `:instance_accessor` option for `class_attribute`. - -* `constantize` now looks in the ancestor chain. - -* Add `Hash#deep_stringify_keys` and `Hash#deep_stringify_keys!` to convert all keys from a `Hash` instance into strings. - -* Add `Hash#deep_symbolize_keys` and `Hash#deep_symbolize_keys!` to convert all keys from a `Hash` instance into symbols. - -* `Object#try` can't call private methods. - -* AS::Callbacks#run_callbacks remove key argument. - -* `deep_dup` works more expectedly now and duplicates also values in `Hash` instances and elements in `Array` instances. - -* Inflector no longer applies ice -> ouse to words like slice, police. - -* Add `ActiveSupport::Deprecations.behavior = :silence` to completely ignore Rails runtime deprecations. - -* Make `Module#delegate` stop using send - can no longer delegate to private methods. - -* AS::Callbacks deprecate :rescuable option. - -* Adds `Integer#ordinal` to get the ordinal suffix string of an integer. - -* AS::Callbacks :per_key option is no longer supported. - -* AS::Callbacks#define_callbacks add :skip_after_callbacks_if_terminated option. - -* Add html_escape_once to ERB::Util, and delegate escape_once tag helper to it. - -* Remove `ActiveSupport::TestCase#pending` method, use `skip` instead. - -* Deletes the compatibility method `Module#method_names`, use `Module#methods` from now on (which returns symbols). - -* Deletes the compatibility method `Module#instance_method_names`, use `Module#instance_methods` from now on (which returns symbols). - -* Unicode database updated to 6.1.0. - -* Adds `encode_big_decimal_as_string` option to force JSON serialization of BigDecimals as numeric instead of wrapping them in strings for safety. +* Allows PostgreSQL hstore records to be created. ### Deprecations -* `ActiveSupport::Callbacks`: deprecate usage of filter object with `#before` and `#after` methods as `around` callback. +* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do. -* `BufferedLogger` is deprecated. Use `ActiveSupport::Logger` or the `logger` from Ruby stdlib. +* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's + how you can rewrite the code: -* Deprecates the compatibility method `Module#local_constant_names` and use `Module#local_constants` instead (which returns symbols). + * `find_all_by_...` can be rewritten using `where(...)`. + * `find_last_by_...` can be rewritten using `where(...).last`. + * `scoped_by_...` can be rewritten using `where(...)`. + * `find_or_initialize_by_...` can be rewritten using `where(...).first_or_initialize`. + * `find_or_create_by_...` can be rewritten using `find_or_create_by(...)` or `where(...).first_or_create`. + * `find_or_create_by_...!` can be rewritten using `find_or_create_by!(...)` or `where(...).first_or_create!`. Credits ------- diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index 9d2e9c1d68..a50961a0c7 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -1,4 +1,4 @@ -<h2>Ruby on Rails Guides (<%= @version %>)</h2> +<h2>Ruby on Rails Guides (<%= @edge ? @version[0, 7] : @version %>)</h2> <% if @edge %> <p> diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index 69d99becb9..46ff9027fd 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -5,13 +5,13 @@ In this guide you will learn how controllers work and how they fit into the requ After reading this guide, you will know: -* Follow the flow of a request through a controller. -* Understand why and how to store data in the session or cookies. -* Work with filters to execute code during request processing. -* Use Action Controller's built-in HTTP authentication. -* Stream data directly to the user's browser. -* Filter sensitive parameters so they do not appear in the application's log. -* Deal with exceptions that may be raised during request processing. +* How to follow the flow of a request through a controller. +* Why and how to store data in the session or cookies. +* How to work with filters to execute code during request processing. +* How to use Action Controller's built-in HTTP authentication. +* How to stream data directly to the user's browser. +* How to filter sensitive parameters so they do not appear in the application's log. +* How to deal with exceptions that may be raised during request processing. -------------------------------------------------------------------------------- @@ -434,7 +434,7 @@ Filters are inherited, so if you set a filter on `ApplicationController`, it wil ```ruby class ApplicationController < ActionController::Base - before_filter :require_login + before_action :require_login private @@ -458,11 +458,11 @@ end The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled. -In this example the filter is added to `ApplicationController` and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter`: +In this example the filter is added to `ApplicationController` and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_action`: ```ruby class LoginsController < ApplicationController - skip_before_filter :require_login, only: [:new, :create] + skip_before_action :require_login, only: [:new, :create] end ``` @@ -480,7 +480,7 @@ For example, in a website where changes have an approval workflow an administrat ```ruby class ChangesController < ActionController::Base - around_filter :wrap_in_transaction, only: :show + around_action :wrap_in_transaction, only: :show private @@ -502,13 +502,13 @@ You can choose not to yield and build the response yourself, in which case the a ### Other Ways to Use Filters -While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing. +While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing. -The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block: +The first is to use a block directly with the *_action methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block: ```ruby class ApplicationController < ActionController::Base - before_filter do |controller| + before_action do |controller| redirect_to new_login_url unless controller.send(:logged_in?) end end @@ -520,7 +520,7 @@ The second way is to use a class (actually, any object that responds to the righ ```ruby class ApplicationController < ActionController::Base - before_filter LoginFilter + before_action LoginFilter end class LoginFilter @@ -648,7 +648,7 @@ HTTP digest authentication is superior to the basic authentication as it does no class AdminController < ApplicationController USERS = { "lifo" => "world" } - before_filter :authenticate + before_action :authenticate private @@ -751,15 +751,36 @@ Now the user can request to get a PDF version of a client just by adding ".pdf" GET /clients/1.pdf ``` -Parameter Filtering -------------------- +Log Filtering +------------- + +Rails keeps a log file for each environment in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. -Rails keeps a log file for each environment in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log. +### Parameters Filtering + +You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log. ```ruby config.filter_parameters << :password ``` +### Redirects Filtering + +Sometimes it's desirable to filter out from log files some sensible locations your application is redirecting to. +You can do that by using the `config.filter_redirect` configuration option: + +```ruby +config.filter_redirect << 's3.amazonaws.com' +``` + +You can set it to a String, a Regexp, or an array of both. + +```ruby +config.filter_redirect.concat ['s3.amazonaws.com', /private_path/] +``` + +Matching URLs will be marked as '[FILTERED]'. + Rescue ------ @@ -807,7 +828,7 @@ end class ClientsController < ApplicationController # Check that the user has the right authorization to access clients. - before_filter :check_authorization + before_action :check_authorization # Note how the actions don't have to worry about all the auth stuff. def edit @@ -828,7 +849,7 @@ NOTE: Certain exceptions are only rescuable from the `ApplicationController` cla Force HTTPS protocol -------------------- -Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use the `force_ssl` method in your controller to enforce that: +Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. You can use the `force_ssl` method in your controller to enforce that: ```ruby class DinnerController @@ -836,7 +857,7 @@ class DinnerController end ``` -Just like the filter, you could also passing `:only` and `:except` to enforce the secure connection only to specific actions: +Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions: ```ruby class DinnerController diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index ddb0e438c9..aaf04f4256 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -5,6 +5,10 @@ This guide should provide you with all you need to get started in sending and re After reading this guide, you will know: +* How to send and receive email within a Rails application. +* How to generate and edit an Action Mailer class and mailer view. +* How to configure Action Mailer for your environment. +* How to test your Action Mailer classes. -------------------------------------------------------------------------------- Introduction @@ -105,7 +109,7 @@ When you call the `mail` method now, Action Mailer will detect the two templates #### Wire It Up So That the System Sends the Email When a User Signs Up -There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, in Rails 3, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created. +There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created. Setting this up is painfully simple. @@ -145,10 +149,6 @@ This provides a much simpler implementation that does not require the registerin The method `welcome_email` returns a `Mail::Message` object which can then just be told `deliver` to send itself out. -NOTE: In previous versions of Rails, you would call `deliver_welcome_email` or `create_welcome_email`. This has been deprecated in Rails 3.0 in favour of just calling the method name itself. - -WARNING: Sending out an email should only take a fraction of a second. If you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job. - ### Auto encoding header values Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies. @@ -447,17 +447,17 @@ end Action Mailer Callbacks --------------------------- -Action Mailer allows for you to specify a `before_filter`, `after_filter` and 'around_filter'. +Action Mailer allows for you to specify a `before_action`, `after_action` and 'around_action'. * Filters can be specified with a block or a symbol to a method in the mailer class similar to controllers. -* You could use a `before_filter` to prepopulate the mail object with defaults, delivery_method_options or insert default headers and attachments. +* You could use a `before_action` to prepopulate the mail object with defaults, delivery_method_options or insert default headers and attachments. -* You could use an `after_filter` to do similar setup as a `before_filter` but using instance variables set in your mailer action. +* You could use an `after_action` to do similar setup as a `before_action` but using instance variables set in your mailer action. ```ruby class UserMailer < ActionMailer::Base - after_filter :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers + after_action :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers def feedback_message(business, user) @business = business diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md index c931b30bd3..6c2871d478 100644 --- a/guides/source/action_view_overview.md +++ b/guides/source/action_view_overview.md @@ -1263,10 +1263,8 @@ Creates a field set for grouping HTML form elements. Creates a file upload field. -Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically. - ```html+erb -<%= form_tag {action: "post"}, {multipart: true} do %> +<%= form_tag {action: "post"} do %> <label for="file">File to Upload</label> <%= file_field_tag "file" %> <%= submit_tag %> <% end %> @@ -1486,7 +1484,7 @@ You can use the same technique to localize the rescue files in your public direc Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to `app/controllers/application.rb`: ```ruby -before_filter :set_expert_locale +before_action :set_expert_locale def set_expert_locale I18n.locale = :expert if current_user.expert? diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md index 0c278095ab..68ac26c681 100644 --- a/guides/source/active_model_basics.md +++ b/guides/source/active_model_basics.md @@ -10,7 +10,7 @@ After reading this guide, you will know: Introduction ------------ -Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below. +Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below. ### AttributeMethods @@ -26,23 +26,21 @@ class Person attr_accessor :age -private - def reset_attribute(attribute) - send("#{attribute}=", 0) - end + private + def reset_attribute(attribute) + send("#{attribute}=", 0) + end - def attribute_highest?(attribute) - send(attribute) > 100 ? true : false - end - + def attribute_highest?(attribute) + send(attribute) > 100 + end end person = Person.new person.age = 110 person.age_highest? # true person.reset_age # 0 -person.age_highest? # false - +person.age_highest? # false ``` ### Callbacks @@ -87,14 +85,14 @@ class Person end person = Person.new -person.to_model == person #=> true -person.to_key #=> nil -person.to_param #=> nil +person.to_model == person # => true +person.to_key # => nil +person.to_param # => nil ``` ### Dirty -An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes first_name and last_name +An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes `first_name` and `last_name`: ```ruby require 'active_model' @@ -123,8 +121,8 @@ class Person def save @previously_changed = changes + # do save work... end - end ``` @@ -132,21 +130,22 @@ end ```ruby person = Person.new -person.first_name = "First Name" +person.changed? # => false -person.first_name #=> "First Name" -person.first_name = "First Name Changed" +person.first_name = "First Name" +person.first_name # => "First Name" -person.changed? #=> true +# returns if any attribute has changed. +person.changed? # => true -#returns an list of fields arry which all has been changed before saved. -person.changed #=> ["first_name"] +# returns a list of attributes that have changed before saving. +person.changed # => ["first_name"] -#returns a hash of the fields that have changed with their original values. -person.changed_attributes #=> {"first_name" => "First Name Changed"} +# returns a hash of the attributes that have changed with their original values. +person.changed_attributes # => {"first_name"=>nil} -#returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field. -person.changes #=> {"first_name" => ["First Name","First Name Changed"]} +# returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field. +person.changes # => {"first_name"=>[nil, "First Name"]} ``` #### Attribute based accessor methods @@ -154,28 +153,24 @@ person.changes #=> {"first_name" => ["First Name","First Name Changed"]} Track whether the particular attribute has been changed or not. ```ruby -#attr_name_changed? -person.first_name #=> "First Name" - -#assign some other value to first_name attribute -person.first_name = "First Name 1" - -person.first_name_changed? #=> true +# attr_name_changed? +person.first_name # => "First Name" +person.first_name_changed? # => true ``` Track what was the previous value of the attribute. ```ruby -#attr_name_was accessor -person.first_name_was #=> "First Name" +# attr_name_was accessor +person.first_name_was # => "First Name" ``` Track both previous and current value of the changed attribute. Returns an array if changed, else returns nil. ```ruby -#attr_name_change -person.first_name_change #=> ["First Name", "First Name 1"] -person.last_name_change #=> nil +# attr_name_change +person.first_name_change # => [nil, "First Name"] +person.last_name_change # => nil ``` ### Validations @@ -187,20 +182,19 @@ class Person include ActiveModel::Validations attr_accessor :name, :email, :token - + validates :name, presence: true - validates_format_of :email, with: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i + validates_format_of :email, with: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i validates! :token, presence: true - end person = Person.new(token: "2b1f325") -person.valid? #=> false -person.name = 'vishnu' -person.email = 'me' -person.valid? #=> false +person.valid? # => false +person.name = 'vishnu' +person.email = 'me' +person.valid? # => false person.email = 'me@vishnuatrai.com' -person.valid? #=> true +person.valid? # => true person.token = nil -person.valid? #=> raises ActiveModel::StrictValidationFailed +person.valid? # => raises ActiveModel::StrictValidationFailed ``` diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index cb64cf39f3..68c6416e89 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -147,15 +147,15 @@ Active Record objects can be created from a hash, a block or have their attribut For example, given a model `User` with attributes of `name` and `occupation`, the `create` method call will create and save a new record into the database: ```ruby - user = User.create(name: "David", occupation: "Code Artist") +user = User.create(name: "David", occupation: "Code Artist") ``` Using the `new` method, an object can be created without being saved: ```ruby - user = User.new - user.name = "David" - user.occupation = "Code Artist" +user = User.new +user.name = "David" +user.occupation = "Code Artist" ``` A call to `user.save` will commit the record to the database. @@ -163,10 +163,10 @@ A call to `user.save` will commit the record to the database. Finally, if a block is provided, both `create` and `new` will yield the new object to that block for initialization: ```ruby - user = User.new do |u| - u.name = "David" - u.occupation = "Code Artist" - end +user = User.new do |u| + u.name = "David" + u.occupation = "Code Artist" +end ``` ### Read @@ -174,23 +174,23 @@ Finally, if a block is provided, both `create` and `new` will yield the new obje Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record. ```ruby - # return array with all records - users = User.all +# return array with all records +users = User.all ``` ```ruby - # return the first record - user = User.first +# return the first record +user = User.first ``` ```ruby - # return the first user named David - david = User.find_by_name('David') +# return the first user named David +david = User.find_by_name('David') ``` ```ruby - # find all users named David who are Code Artists and sort by created_at in reverse chronological order - users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC') +# find all users named David who are Code Artists and sort by created_at in reverse chronological order +users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC') ``` You can learn more about querying an Active Record model in the [Active Record Query Interface](active_record_querying.html) guide. @@ -200,9 +200,9 @@ You can learn more about querying an Active Record model in the [Active Record Q Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database. ```ruby - user = User.find_by_name('David') - user.name = 'Dave' - user.save +user = User.find_by_name('David') +user.name = 'Dave' +user.save ``` ### Delete @@ -210,8 +210,8 @@ Once an Active Record object has been retrieved, its attributes can be modified Likewise, once retrieved an Active Record object can be destroyed which removes it from the database. ```ruby - user = User.find_by_name('David') - user.destroy +user = User.find_by_name('David') +user.destroy ``` Validations diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index c45f3f2e6a..971c1cdb25 100644 --- a/guides/source/active_record_callbacks.md +++ b/guides/source/active_record_callbacks.md @@ -4,11 +4,11 @@ Active Record Callbacks This guide teaches you how to hook into the life cycle of your Active Record objects. -After reading this guide and trying out the presented concepts, we hope that you'll be able to: +After reading this guide, you will know: -* Understand the life cycle of Active Record objects -* Create callback methods that respond to events in the object life cycle -* Create special classes that encapsulate common behavior for your callbacks +* The life cycle of Active Record objects. +* How to create callback methods that respond to events in the object life cycle. +* How to create special classes that encapsulate common behavior for your callbacks. -------------------------------------------------------------------------------- @@ -200,7 +200,7 @@ Halting Execution As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed. -The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception. +The whole callback chain is wrapped in a transaction. If any _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception. WARNING. Raising an arbitrary exception may break code that expects `save` and its friends not to fail like that. The `ActiveRecord::Rollback` exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised. diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 9620270141..24f98f68ca 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -5,13 +5,13 @@ This guide covers different ways to retrieve data from the database using Active After reading this guide, you will know: -* Find records using a variety of methods and conditions. -* Specify the order, retrieved attributes, grouping, and other properties of the found records. -* Use eager loading to reduce the number of database queries needed for data retrieval. -* Use dynamic finders methods. -* Check for the existence of particular records. -* Perform various calculations on Active Record models. -* Run EXPLAIN on relations. +* How to find records using a variety of methods and conditions. +* How to specify the order, retrieved attributes, grouping, and other properties of the found records. +* How to use eager loading to reduce the number of database queries needed for data retrieval. +* How to use dynamic finders methods. +* How to check for the existence of particular records. +* How to perform various calculations on Active Record models. +* How to run EXPLAIN on relations. -------------------------------------------------------------------------------- @@ -505,6 +505,20 @@ This code will generate SQL like this: SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) ``` +### NOT, LIKE, and NOT LIKE Conditions + +`NOT`, `LIKE`, and `NOT LIKE` SQL queries can be built by `where.not`, `where.like`, and `where.not_like` respectively. + +```ruby +Post.where.not(author: author) + +Author.where.like(name: 'Nari%') + +Developer.where.not_like(name: 'Tenderl%') +``` + +In other words, these sort of queries can be generated by calling `where` with no argument, then immediately chain with `not`, `like`, or `not_like` passing `where` conditions. + Ordering -------- @@ -1190,7 +1204,7 @@ class Client < ActiveRecord::Base end ``` -### Removing all scoping +### Removing All Scoping If we wish to remove scoping for any reason we can use the `unscoped` method. This is especially useful if a `default_scope` is specified in the model and should not be @@ -1222,9 +1236,7 @@ You can specify an exclamation point (`!`) on the end of the dynamic finders to If you want to find both by name and locked, you can chain these finders together by simply typing "`and`" between the fields. For example, `Client.find_by_first_name_and_locked("Ryan", true)`. -WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say `Client.find_by_name_and_locked("Ryan")`, the behavior is to pass `nil` as the missing argument. This is **unintentional** and this behavior will be changed in Rails 3.2 to throw an `ArgumentError`. - -Find or build a new object +Find or Build a New Object -------------------------- It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods. diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index e752c6f3f9..2e2f0e4ea9 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -6,9 +6,9 @@ the database using Active Record's validations feature. After reading this guide, you will know: -* Use the built-in Active Record validation helpers -* Create your own custom validation methods -* Work with the error messages generated by the validation process +* How to use the built-in Active Record validation helpers. +* How to create your own custom validation methods. +* How to work with the error messages generated by the validation process. -------------------------------------------------------------------------------- @@ -264,7 +264,7 @@ class Person < ActiveRecord::Base end ``` -The default error message for this helper is "_must be accepted_". +The default error message for this helper is _"must be accepted"_. It can receive an `:accept` option, which determines the value that will be considered acceptance. It defaults to "1" and can be easily changed. @@ -293,7 +293,7 @@ This validation will work with all of the association types. CAUTION: Don't use `validates_associated` on both ends of your associations. They would call each other in an infinite loop. -The default error message for `validates_associated` is "_is invalid_". Note +The default error message for `validates_associated` is _"is invalid"_. Note that each associated object will contain its own `errors` collection; errors do not bubble up to the calling model. @@ -328,7 +328,7 @@ class Person < ActiveRecord::Base end ``` -The default error message for this helper is "_doesn't match confirmation_". +The default error message for this helper is _"doesn't match confirmation"_. ### `exclusion` @@ -348,7 +348,7 @@ alias called `:within` that you can use for the same purpose, if you'd like to. This example uses the `:message` option to show how you can include the attribute's value. -The default error message is "_is reserved_". +The default error message is _"is reserved"_. ### `format` @@ -362,7 +362,7 @@ class Product < ActiveRecord::Base end ``` -The default error message is "_is invalid_". +The default error message is _"is invalid"_. ### `inclusion` @@ -381,7 +381,7 @@ will be accepted. The `:in` option has an alias called `:within` that you can use for the same purpose, if you'd like to. The previous example uses the `:message` option to show how you can include the attribute's value. -The default error message for this helper is "_is not included in the list_". +The default error message for this helper is _"is not included in the list"_. ### `length` @@ -471,24 +471,24 @@ Besides `:only_integer`, this helper also accepts the following options to add constraints to acceptable values: * `:greater_than` - Specifies the value must be greater than the supplied - value. The default error message for this option is "_must be greater than - %{count}_". + value. The default error message for this option is _"must be greater than + %{count}"_. * `:greater_than_or_equal_to` - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is - "_must be greater than or equal to %{count}_". + _"must be greater than or equal to %{count}"_. * `:equal_to` - Specifies the value must be equal to the supplied value. The - default error message for this option is "_must be equal to %{count}_". + default error message for this option is _"must be equal to %{count}"_. * `:less_than` - Specifies the value must be less than the supplied value. The - default error message for this option is "_must be less than %{count}_". + default error message for this option is _"must be less than %{count}"_. * `:less_than_or_equal_to` - Specifies the value must be less than or equal the - supplied value. The default error message for this option is "_must be less - than or equal to %{count}_". + supplied value. The default error message for this option is _"must be less + than or equal to %{count}"_. * `:odd` - Specifies the value must be an odd number if set to true. The - default error message for this option is "_must be odd_". + default error message for this option is _"must be odd"_. * `:even` - Specifies the value must be an even number if set to true. The - default error message for this option is "_must be even_". + default error message for this option is _"must be even"_. -The default error message is "_is not a number_". +The default error message is _"is not a number"_. ### `presence` @@ -528,7 +528,7 @@ If you validate the presence of an object associated via a `has_one` or Since `false.blank?` is true, if you want to validate the presence of a boolean field you should use `validates :field_name, inclusion: { in: [true, false] }`. -The default error message is "_can't be empty_". +The default error message is _"can't be empty"_. ### `uniqueness` @@ -570,7 +570,7 @@ end WARNING. Note that some databases are configured to perform case-insensitive searches anyway. -The default error message is "_has already been taken_". +The default error message is _"has already been taken"_. ### `validates_with` @@ -714,7 +714,7 @@ class Person < ActiveRecord::Base validates :name, presence: { strict: true } end -Person.new.valid? #=> ActiveModel::StrictValidationFailed: Name can't be blank +Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank ``` There is also an ability to pass custom exception to `:strict` option @@ -724,7 +724,7 @@ class Person < ActiveRecord::Base validates :token, presence: true, uniqueness: true, strict: TokenGenerationException end -Person.new.valid? #=> TokenGenerationException: Token can't be blank +Person.new.valid? # => TokenGenerationException: Token can't be blank ``` Conditional Validation @@ -779,7 +779,7 @@ class Account < ActiveRecord::Base end ``` -### Grouping conditional validations +### Grouping Conditional validations Sometimes it is useful to have multiple validations use one condition, it can be easily achieved using `with_options`. @@ -796,7 +796,7 @@ end All validations inside of `with_options` block will have automatically passed the condition `if: :is_admin?` -### Combining validation conditions +### Combining Validation Conditions On the other hand, when multiple conditions define whether or not a validation should happen, an `Array` can be used. Moreover, you can apply both `:if` and @@ -917,7 +917,7 @@ validations fail. Because every application handles this kind of thing differently, Rails does not include any view helpers to help you generate these messages directly. -However, due to the rich number of methods Rails gives you to interact with +However, due to the rich number of methods Rails gives you to interact with validations in general, it's fairly easy to build your own. In addition, when generating a scaffold, Rails will put some ERB into the `_form.html.erb` that it generates that displays the full list of errors on that model. diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 775da2a85c..1d79ee2565 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -7,6 +7,11 @@ It offers a richer bottom-line at the language level, targeted both at the devel 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. + -------------------------------------------------------------------------------- How to Load Core Extensions @@ -1120,8 +1125,6 @@ C.subclasses # => [B, D] The order in which these classes are returned is unspecified. -WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1. - NOTE: Defined in `active_support/core_ext/class/subclasses.rb`. #### `descendants` @@ -1157,7 +1160,7 @@ Inserting data into HTML templates needs extra care. For example, you can't just #### Safe Strings -Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not. +Active Support has the concept of <i>(html) safe</i> strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not. Strings are considered to be <i>unsafe</i> by default: @@ -1194,10 +1197,10 @@ Safe arguments are directly appended: "".html_safe + "<".html_safe # => "<" ``` -These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped: +These methods should not be used in ordinary views. Unsafe values are automatically escaped: ```erb -<%= @review.title %> <%# fine in Rails 3, escaped if needed %> +<%= @review.title %> <%# fine, escaped if needed %> ``` To insert something verbatim use the `raw` helper rather than calling `html_safe`: diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md index 0126fc94d1..d0499878da 100644 --- a/guides/source/api_documentation_guidelines.md +++ b/guides/source/api_documentation_guidelines.md @@ -5,6 +5,9 @@ This guide documents the Ruby on Rails API documentation guidelines. After reading this guide, you will know: +* How to write effective prose for documentation purposes. +* Style guidelines for documenting different kinds of Ruby code. + -------------------------------------------------------------------------------- RDoc diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index fa4e714950..ff6787dae5 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -1,15 +1,15 @@ The Asset Pipeline ================== -This guide covers the asset pipeline introduced in Rails 3.1. +This guide covers the asset pipeline. After reading this guide, you will know: -* Understand what the asset pipeline is and what it does. -* Properly organize your application assets. -* Understand the benefits of the asset pipeline. -* Add a pre-processor to the pipeline. -* Package assets with a gem. +* How to understand what the asset pipeline is and what it does. +* How to properly organize your application assets. +* How to understand the benefits of the asset pipeline. +* How to add a pre-processor to the pipeline. +* How to package assets with a gem. -------------------------------------------------------------------------------- @@ -18,11 +18,9 @@ What is the Asset Pipeline? The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. -Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the `sprockets` gem, by default. - Making the asset pipeline a core feature of Rails means that all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011. -In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition: +The asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition: ```ruby config.assets.enabled = false @@ -100,7 +98,24 @@ In production, Rails precompiles these files to `public/assets` by default. The When you generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`) for that controller. -For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`. +For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`. Note that you have to set `config.assets.precompile` in `config/environments/production.rb` if you want to precomepile them and use in production mode. You can append them one by one or do something like this: + + # config/environments/production.rb + config.assets.precompile << Proc.new { |path| + if path =~ /\.(css|js)\z/ + full_path = Rails.application.assets.resolve(path).to_path + app_assets_path = Rails.root.join('app', 'assets').to_path + if full_path.starts_with? app_assets_path + puts "including asset: " + full_path + true + else + puts "excluding asset: " + full_path + false + end + else + false + end + } NOTE: You must have an [ExecJS](https://github.com/sstephenson/execjs#readme) supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check [ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all supported JavaScript runtimes. @@ -114,7 +129,7 @@ Pipeline assets can be placed inside an application in one of three locations: ` * `vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks. -#### Search paths +#### Search Paths When a file is referenced from a manifest or a helper, Sprockets searches the three default asset locations for it. @@ -162,7 +177,7 @@ Paths are traversed in the order that they occur in the search path. By default, It is important to note that files you want to reference outside a manifest must be added to the precompile array or they will not be available in the production environment. -#### Using index files +#### Using Index Files Sprockets uses files named `index` (with the relevant extensions) for a special purpose. @@ -270,8 +285,6 @@ For example, a new Rails application includes a default `app/assets/javascripts/ In JavaScript files, the directives begin with `//=`. In this case, the file is using the `require` and the `require_tree` directives. The `require` directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a `.js` file when done from within a `.js` file. -NOTE. In Rails 3.1 the `jquery-rails` gem provides the `jquery.js` and `jquery_ujs.js` files via the asset pipeline. You won't see them in the application tree. - The `require_tree` directive tells Sprockets to recursively include _all_ JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the `require_directory` directive which includes all JavaScript files only in the directory specified, without recursion. Directives are processed top to bottom, but the order in which files are included by `require_tree` is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other in the concatenated file, require the prerequisite file first in the manifest. Note that the family of `require` directives prevents files from being included twice in the output. @@ -337,7 +350,7 @@ would generate this HTML: The `body` param is required by Sprockets. -### Turning Debugging off +### Turning Debugging Off You can turn off debug mode by updating `config/environments/development.rb` to include: @@ -462,7 +475,7 @@ The default location for the manifest is the root of the location specified in ` NOTE: If there are missing precompiled files in production you will get an `Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError` exception indicating the name of the missing file(s). -#### Far-future Expires header +#### Far-future Expires Header Precompiled assets exist on the filesystem and are served directly by your web server. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add them. @@ -492,7 +505,7 @@ location ~ ^/assets/ { } ``` -#### GZip compression +#### GZip Compression When files are precompiled, Sprockets also creates a [gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. On the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves. @@ -648,7 +661,7 @@ This can be changed to something else: config.assets.prefix = "/some_other_path" ``` -This is a handy option if you are updating an existing project (pre Rails 3.1) that already uses this path or you wish to use this path for a new resource. +This is a handy option if you are updating an older project that didn't use the asset pipeline and that already uses this path or you wish to use this path for a new resource. ### X-Sendfile Headers diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 43d3b20165..95adb4ff0a 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -5,9 +5,9 @@ This guide covers the association features of Active Record. After reading this guide, you will know: -* Declare associations between Active Record models. -* Understand the various types of Active Record associations. -* Use the methods added to your models by creating associations. +* How to declare associations between Active Record models. +* How to understand the various types of Active Record associations. +* How to use the methods added to your models by creating associations. -------------------------------------------------------------------------------- @@ -452,7 +452,7 @@ class CreateAssemblyPartJoinTable < ActiveRecord::Migration end ``` -We pass `id: false` to `create_table` because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit. +We pass `id: false` to `create_table` because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled models IDs, or exceptions about conflicting IDs, chances are you forgot that bit. ### Controlling Association Scope diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index e737dcab83..773102400a 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -104,7 +104,7 @@ Let's say you only wanted authenticated users to call actions on `ProductsContro ```ruby class ProductsController < ActionController - before_filter :authenticate + before_action :authenticate caches_action :index def index diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 0a4a704cd9..746226fa96 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -5,11 +5,11 @@ Rails comes with every command line tool you'll need to After reading this guide, you will know: -* Create a Rails application. -* Generate models, controllers, database migrations, and unit tests. -* Start a development server. -* Experiment with objects through an interactive shell. -* Profile and benchmark your new creation. +* How to create a Rails application. +* How to generate models, controllers, database migrations, and unit tests. +* How to start a development server. +* How to experiment with objects through an interactive shell. +* How to profile and benchmark your new creation. -------------------------------------------------------------------------------- diff --git a/guides/source/configuring.md b/guides/source/configuring.md index dba2be3b71..446f767f0c 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -5,8 +5,8 @@ This guide covers the configuration and initialization features available to Rai After reading this guide, you will know: -* Adjust the behavior of your Rails applications. -* Add additional code to be run at application start time. +* How to adjust the behavior of your Rails applications. +* How to add additional code to be run at application start time. -------------------------------------------------------------------------------- @@ -135,8 +135,6 @@ These configuration methods are to be called on a `Rails::Railtie` object, such ### Configuring Assets -Rails 3.1 and up, by default, is set up to use the `sprockets` gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful. - * `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`. @@ -165,7 +163,7 @@ Rails 3.1 and up, by default, is set up to use the `sprockets` gem to manage ass ### Configuring Generators -Rails 3 allows you to alter what generators are used with the `config.generators` method. This method takes a block: +Rails allows you to alter what generators are used with the `config.generators` method. This method takes a block: ```ruby config.generators do |g| diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index fa6c335088..ce2a5a4902 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -5,11 +5,11 @@ This guide covers ways in which _you_ can become a part of the ongoing developme After reading this guide, you will know: -* Using GitHub to report issues. -* Cloning master and running the test suite. -* Helping to resolve existing issues. -* Contributing to the Ruby on Rails documentation. -* Contributing to the Ruby on Rails code. +* How to use GitHub to report issues. +* How to clone master and run the test suite. +* How to help resolve existing issues. +* How to contribute to the Ruby on Rails documentation. +* How to contribute to the Ruby on Rails code. Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation — all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches. @@ -91,7 +91,7 @@ You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` als The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings. -As of this writing (December, 2010) they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag: +As of this writing (December, 2010) they are especially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag: ```bash $ RUBYOPT=-W0 bundle exec rake test @@ -205,7 +205,7 @@ TIP: Changes that are cosmetic in nature and do not add anything substantial to ### Follow the Coding Conventions -Rails follows a simple set of coding style conventions. +Rails follows a simple set of coding style conventions: * Two spaces, no tabs (for indentation). * No trailing whitespace. Blank lines should not have any spaces. diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 96112da50f..addc3a63a8 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -5,10 +5,10 @@ This guide introduces techniques for debugging Ruby on Rails applications. After reading this guide, you will know: -* Understand the purpose of debugging. -* Track down problems and issues in your application that your tests aren't identifying. -* Learn the different ways of debugging. -* Analyze the stack trace. +* The purpose of debugging. +* How to track down problems and issues in your application that your tests aren't identifying. +* The different ways of debugging. +* How to analyze the stack trace. -------------------------------------------------------------------------------- diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md index 79d59859c8..db43d62fcf 100644 --- a/guides/source/development_dependencies_install.md +++ b/guides/source/development_dependencies_install.md @@ -145,6 +145,9 @@ We need first to delete `.bundle/config` because Bundler remembers in that file In order to be able to run the test suite against MySQL you need to create a user named `rails` with privileges on the test databases: ```bash +$ mysql -uroot -p + +mysql> CREATE USER 'rails'@'localhost'; mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* to 'rails'@'localhost'; mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* diff --git a/guides/source/engines.md b/guides/source/engines.md index f1e2780eae..116a7e67cd 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -35,7 +35,7 @@ Finally, engines would not have been possible without the work of James Adam, Pi Generating an engine -------------------- -To generate an engine with Rails 3.2, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal: +To generate an engine, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal: ```bash $ rails plugin new blorgh --mountable diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md index b89d776d87..ee563e72d5 100644 --- a/guides/source/form_helpers.md +++ b/guides/source/form_helpers.md @@ -5,13 +5,13 @@ Forms in web applications are an essential interface for user input. However, fo After reading this guide, you will know: -* Create search forms and similar kind of generic forms not representing any specific model in your application. -* Make model-centric forms for creation and editing of specific database records. -* Generate select boxes from multiple types of data. -* Understand the date and time helpers Rails provides. -* Learn what makes a file upload form different. -* Learn some cases of building forms to external resources. -* Find out how to build complex forms. +* How to create search forms and similar kind of generic forms not representing any specific model in your application. +* How to make model-centric forms for creation and editing of specific database records. +* How to generate select boxes from multiple types of data. +* The date and time helpers Rails provides. +* What makes a file upload form different. +* Some cases of building forms to external resources. +* How to build complex forms. -------------------------------------------------------------------------------- @@ -594,8 +594,6 @@ The following two forms both upload a file. <% end %> ``` -NOTE: Since Rails 3.1, forms rendered using `form_for` have their encoding set to `multipart/form-data` automatically once a `file_field` is used inside the block. Previous versions required you to set this explicitly. - Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in `params[:picture]` and in the second case in `params[:person][:picture]`. ### What Gets Uploaded diff --git a/guides/source/generators.md b/guides/source/generators.md index f83f5c6691..62de5a70bb 100644 --- a/guides/source/generators.md +++ b/guides/source/generators.md @@ -5,18 +5,16 @@ Rails generators are an essential tool if you plan to improve your workflow. Wit After reading this guide, you will know: -* Learn how to see which generators are available in your application. -* Create a generator using templates. -* Learn how Rails searches for generators before invoking them. -* Customize your scaffold by creating new generators. -* Customize your scaffold by changing generator templates. -* Learn how to use fallbacks to avoid overwriting a huge set of generators. -* Learn how to create an application template. +* How to see which generators are available in your application. +* How to create a generator using templates. +* How Rails searches for generators before invoking them. +* How to customize your scaffold by creating new generators. +* How to customize your scaffold by changing generator templates. +* How to use fallbacks to avoid overwriting a huge set of generators. +* How to create an application template. -------------------------------------------------------------------------------- -NOTE: This guide is about generators in Rails 3, previous versions are not covered. - First Contact ------------- diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index ceba2c65aa..54200768e6 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -5,7 +5,7 @@ This guide covers getting up and running with Ruby on Rails. After reading this guide, you will know: -* Installing Rails, creating a new Rails application, and connecting your +* How to install Rails, create a new Rails application, and connect your application to a database. * The general layout of a Rails application. * The basic principles of MVC (Model, View, Controller) and RESTful design. @@ -77,7 +77,7 @@ TIP: The examples below use # and $ to denote superuser and regular user termina Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose "Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a -dollar sign `$` should be run in the command line. Verify sure you have a +dollar sign `$` should be run in the command line. Verify that you have a current version of Ruby installed: ```bash @@ -101,11 +101,11 @@ To verify that you have everything installed correctly, you should be able to ru $ rails --version ``` -If it says something like "Rails 3.2.9" you are ready to continue. +If it says something like "Rails 3.2.9", you are ready to continue. ### Creating the Blog Application -Rails comes with a number of generators that are designed to make your development life easier. One of these is the new application generator, which will provide you with the foundation of a Rails application so that you don't have to write it yourself. +Rails comes with a number of scripts called generators that are designed to make your development life easier by creating everything that's necessary to start working on a particular task. One of these is the new application generator, which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself. To use this generator, open a terminal, navigate to a directory where you have rights to create files, and type: @@ -520,7 +520,7 @@ invoking the command: `rake db:migrate RAILS_ENV=production`. ### Saving data in the controller Back in `posts_controller`, we need to change the `create` action -to use the new `Post` model to save the data in the database. Open that file +to use the new `Post` model to save the data in the database. Open `app/controllers/posts_controller.rb` and change the `create` action to look like this: ```ruby @@ -558,8 +558,8 @@ 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. -As we did before, we need to add the `show` action in the -`posts_controller` and its respective view. +As we did before, we need to add the `show` action in +`app/controllers/posts_controller.rb` and its respective view. ```ruby def show @@ -1216,7 +1216,7 @@ This command will generate four files: | test/models/comment_test.rb | Testing harness for the comments model | | test/fixtures/comments.yml | Sample comments for use in testing | -First, take a look at `comment.rb`: +First, take a look at `app/models/comment.rb`: ```ruby class Comment < ActiveRecord::Base @@ -1277,7 +1277,7 @@ this way: * One post can have many comments. In fact, this is very close to the syntax that Rails uses to declare this -association. You've already seen the line of code inside the `Comment` model that +association. You've already seen the line of code inside the `Comment` model (app/models/comment.rb) that makes each comment belong to a Post: ```ruby @@ -1286,7 +1286,7 @@ class Comment < ActiveRecord::Base end ``` -You'll need to edit the `post.rb` file to add the other side of the association: +You'll need to edit `app/models/post.rb` to add the other side of the association: ```ruby class Post < ActiveRecord::Base @@ -1350,7 +1350,7 @@ the post show page to see their comment now listed. Due to this, our spam comments when they arrive. So first, we'll wire up the Post show template -(`/app/views/posts/show.html.erb`) to let us make a new comment: +(`app/views/posts/show.html.erb`) to let us make a new comment: ```html+erb <p> @@ -1609,7 +1609,7 @@ So first, let's add the delete link in the Clicking this new "Destroy Comment" link will fire off a `DELETE /posts/:post_id/comments/:id` to our `CommentsController`, which can then use this to find the comment we want to delete, so let's add a destroy action to our -controller: +controller (`app/controllers/comments_controller.rb`): ```ruby class CommentsController < ApplicationController @@ -1667,7 +1667,7 @@ action if that method allows it. To use the authentication system, we specify it at the top of our `PostsController`, in this case, we want the user to be authenticated on every -action, except for `index` and `show`, so we write that: +action, except for `index` and `show`, so we write that in `app/controllers/posts_controller.rb`: ```ruby class PostsController < ApplicationController @@ -1682,7 +1682,7 @@ class PostsController < ApplicationController ``` We also only want to allow authenticated users to delete comments, so in the -`CommentsController` we write: +`CommentsController` (`app/controllers/comments_controller.rb`) we write: ```ruby class CommentsController < ApplicationController diff --git a/guides/source/i18n.md b/guides/source/i18n.md index e1cf21f039..399a4963d7 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -134,10 +134,10 @@ However, you would probably like to **provide support for more locales** in your WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [<em>RESTful</em>](http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below. -The _setting part_ is easy. You can set the locale in a `before_filter` in the `ApplicationController` like this: +The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this: ```ruby -before_filter :set_locale +before_action :set_locale def set_locale I18n.locale = params[:locale] || I18n.default_locale @@ -160,7 +160,7 @@ One option you have is to set the locale from the domain name where your applica You can implement it like this in your `ApplicationController`: ```ruby -before_filter :set_locale +before_action :set_locale def set_locale I18n.locale = extract_locale_from_tld || I18n.default_locale @@ -203,7 +203,7 @@ This solution has aforementioned advantages, however, you may not be able or may ### Setting the Locale from the URL Params -The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_filter_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case. +The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_action_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case. This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though. @@ -696,7 +696,7 @@ en: long: "%B %d, %Y" ``` -So, all of the following equivalent lookups will return the `:short` date format `"%B %d"`: +So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`: ```ruby I18n.t 'date.formats.short' diff --git a/guides/source/index.html.erb b/guides/source/index.html.erb index 71fe94a870..a8e4525c67 100644 --- a/guides/source/index.html.erb +++ b/guides/source/index.html.erb @@ -9,9 +9,7 @@ Ruby on Rails Guides <% content_for :index_section do %> <div id="subCol"> <dl> - <dd class="kindle">Rails Guides are also available for Kindle and <%= link_to 'Free Kindle Reading Apps', 'http://www.amazon.com/gp/kindle/kcp' %> for the iPad, -iPhone, Mac, Android, etc. Download them from <%= link_to 'here', @mobi %>. - </dd> + <dd class="kindle">Rails Guides are also available for <%= link_to 'Kindle', @mobi %>.</dd> <dd class="work-in-progress">Guides marked with this icon are currently being worked on and will not be available in the Guides Index menu. While still useful, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections.</dd> </dl> </div> diff --git a/guides/source/initialization.md b/guides/source/initialization.md index 6a34125654..32df508f9c 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -6,7 +6,7 @@ as of Rails 4. It is an extremely in-depth guide and recommended for advanced Ra After reading this guide, you will know: -* Using `rails server`. +* How to use `rails server`. -------------------------------------------------------------------------------- diff --git a/guides/source/kindle/rails_guides.opf.erb b/guides/source/kindle/rails_guides.opf.erb index 4e07664fd0..547abcbc19 100644 --- a/guides/source/kindle/rails_guides.opf.erb +++ b/guides/source/kindle/rails_guides.opf.erb @@ -32,7 +32,7 @@ <item id="toc" media-type="application/x-dtbncx+xml" href="toc.ncx" /> - <item id="cover" media-type="image/jpeg" href="images/rails_guides_kindle_cover.jpg"/> + <item id="cover" media-type="image/jpg" href="images/rails_guides_kindle_cover.jpg"/> </manifest> <spine toc="toc"> diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index 394ef794d3..dbaa3ec576 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -5,10 +5,10 @@ This guide covers the basic layout features of Action Controller and Action View After reading this guide, you will know: -* Use the various rendering methods built into Rails. -* Create layouts with multiple content sections. -* Use partials to DRY up your views. -* Use nested layouts (sub-templates). +* How to use the various rendering methods built into Rails. +* How to create layouts with multiple content sections. +* How to use partials to DRY up your views. +* How to use nested layouts (sub-templates). -------------------------------------------------------------------------------- @@ -160,21 +160,6 @@ def update end ``` -To be explicit, you can use `render` with the `:action` option (though this is no longer necessary in Rails 3.0): - -```ruby -def update - @book = Book.find(params[:id]) - if @book.update_attributes(params[:book]) - redirect_to(@book) - else - render action: "edit" - end -end -``` - -WARNING: Using `render` with `:action` is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does _not_ run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling `render`. - #### Rendering an Action's Template from Another Controller What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with `render`, which accepts the full path (relative to `app/views`) of the template to render. For example, if you're running code in an `AdminProductsController` that lives in `app/controllers/admin`, you can render the results of an action to a template in `app/views/products` this way: @@ -674,7 +659,7 @@ There are three tag options available for the `auto_discovery_link_tag`: The `javascript_include_tag` helper returns an HTML `script` tag for each source provided. -If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the Sprockets gem, which was introduced in Rails 3.1. +If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline. A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization) @@ -843,7 +828,7 @@ You can even use dynamic paths such as `cache/#{current_site}/main/display`. The `image_tag` helper builds an HTML `<img />` tag to the specified file. By default, files are loaded from `public/images`. -WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append `.png` if no extension was given but Rails 3.0 does not. +WARNING: Note that you must specify the extension of the image. ```erb <%= image_tag "header.png" %> @@ -1091,8 +1076,6 @@ Every partial also has a local variable with the same name as the partial (minus Within the `customer` partial, the `customer` variable will refer to `@new_customer` from the parent view. -WARNING: In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior was deprecated in 2.3 and has been removed in Rails 3.0. - If you have an instance of a model to render into a partial, you can use a shorthand syntax: ```erb @@ -1120,7 +1103,7 @@ Partials are very useful in rendering collections. When you pass a collection to When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within the `_product` partial, you can refer to `product` to get the instance that is being rendered. -In Rails 3.0, there is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result: +There is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result: ```html+erb <h1>Products</h1> diff --git a/guides/source/migrations.md b/guides/source/migrations.md index 7c6c2ee18e..9840e7694f 100644 --- a/guides/source/migrations.md +++ b/guides/source/migrations.md @@ -334,7 +334,7 @@ end removes the `description` and `name` columns, creates a `part_number` string column and adds an index on it. Finally it renames the `upccode` column. -### When Helpers Aren't Enough +### When Helpers aren't Enough If the helpers provided by Active Record aren't enough you can use the `execute` method to execute arbitrary SQL: @@ -433,7 +433,7 @@ no such migrations, it exits. It will run these migrations in order based on the date of the migration. Note that running the `db:migrate` also invokes the `db:schema:dump` task, which -will update your db/schema.rb file to match the structure of your database. +will update your `db/schema.rb` file to match the structure of your database. If you specify a target version, Active Record will run the required migrations (up, down or change) until it has reached the specified version. The version @@ -585,8 +585,8 @@ Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run `rake db:migrate`. You must rollback the migration (for -example with `rake db:rollback`), edit your migration and then run `rake -db:migrate` to run the corrected version. +example with `rake db:rollback`), edit your migration and then run +`rake db:migrate` to run the corrected version. In general, editing existing migrations is not a good idea. You will be creating extra work for yourself and your co-workers and cause major headaches diff --git a/guides/source/performance_testing.md b/guides/source/performance_testing.md index a07f64ec29..182f7eb0fd 100644 --- a/guides/source/performance_testing.md +++ b/guides/source/performance_testing.md @@ -6,12 +6,12 @@ application. After reading this guide, you will know: -* Understand the various types of benchmarking and profiling metrics. -* Generate performance and benchmarking tests. -* Install and use a GC-patched Ruby binary to measure memory usage and object +* The various types of benchmarking and profiling metrics. +* How to generate performance and benchmarking tests. +* How to install and use a GC-patched Ruby binary to measure memory usage and object allocation. -* Understand the benchmarking information provided by Rails inside the log files. -* Learn about various tools facilitating benchmarking and profiling. +* The benchmarking information provided by Rails inside the log files. +* Various tools facilitating benchmarking and profiling. Performance testing is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page diff --git a/guides/source/plugins.md b/guides/source/plugins.md index c7c843ec3a..f8f04c3c67 100644 --- a/guides/source/plugins.md +++ b/guides/source/plugins.md @@ -9,8 +9,8 @@ A Rails plugin is either an extension or a modification of the core framework. P After reading this guide, you will know: -* Creating a plugin from scratch. -* Writing and running tests for the plugin. +* How to create a plugin from scratch. +* How to write and run tests for the plugin. This guide describes how to build a test-driven plugin that will: @@ -27,16 +27,13 @@ goodness. Setup ----- -_"vendored plugins"_ were available in previous versions of Rails, but they are deprecated in -Rails 3.2, and will not be available in the future. - Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared across different rails applications using RubyGems and Bundler if desired. ### Generate a gemified plugin. -Rails 3.1 ships with a `rails plugin new` command which creates a +Rails ships with a `rails plugin new` command which creates a skeleton for developing any kind of Rails extension with the ability to run integration tests using a dummy Rails application. See usage and options by asking for help: diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md index 83c563ac78..9e694acb98 100644 --- a/guides/source/rails_application_templates.md +++ b/guides/source/rails_application_templates.md @@ -5,8 +5,8 @@ Application templates are simple Ruby files containing DSL for adding gems/initi After reading this guide, you will know: -* Use templates to generate/customize Rails applications. -* Write your own reusable application templates using the Rails template API. +* How to use templates to generate/customize Rails applications. +* How to write your own reusable application templates using the Rails template API. -------------------------------------------------------------------------------- diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 531b35a973..1fac6d9883 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -5,10 +5,10 @@ This guide covers Rails integration with Rack and interfacing with other Rack co After reading this guide, you will know: -* Create Rails Metal applications. -* Use Rack Middlewares in your Rails applications. -* Understand Action Pack's internal Middleware stack. -* Define a custom Middleware stack. +* How to create Rails Metal applications. +* How to use Rack Middlewares in your Rails applications. +* Action Pack's internal Middleware stack. +* How to define a custom Middleware stack. -------------------------------------------------------------------------------- diff --git a/guides/source/routing.md b/guides/source/routing.md index 7d43854f2f..241a7cfec6 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -5,11 +5,11 @@ This guide covers the user-facing features of Rails routing. After reading this guide, you will know: -* Understand the code in `routes.rb`. -* Construct your own routes, using either the preferred resourceful style or the `match` method. -* Identify what parameters to expect an action to receive. -* Automatically create paths and URLs using route helpers. -* Use advanced techniques such as constraints and Rack endpoints. +* How to interpret the code in `routes.rb`. +* How to construct your own routes, using either the preferred resourceful style or the `match` method. +* What parameters to expect an action to receive. +* How to automatically create paths and URLs using route helpers. +* Advanced techniques such as constraints and Rack endpoints. -------------------------------------------------------------------------------- @@ -20,13 +20,13 @@ The Rails router recognizes URLs and dispatches them to a controller's action. I ### Connecting URLs to Code -When your Rails application receives an incoming request +When your Rails application receives an incoming request for: ``` GET /patients/17 ``` -it asks the router to match it to a controller action. If the first matching route is +it asks the router to match it to a controller action. If the first matching route is: ```ruby get '/patients/:id', to: 'patients#show' @@ -36,23 +36,25 @@ the request is dispatched to the `patients` controller's `show` action with `{ i ### Generating Paths and URLs from Code -You can also generate paths and URLs. If the route above is modified to be +You can also generate paths and URLs. If the route above is modified to be: ```ruby get '/patients/:id', to: 'patients#show', as: 'patient' ``` -If your application contains this code: +and your application contains this code in the controller: ```ruby @patient = Patient.find(17) ``` +and this in the corresponding view: + ```erb <%= link_to 'Patient Record', patient_path(@patient) %> ``` -The router will generate the path `/patients/17`. This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper. +then the router will generate the path `/patients/17`. This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper. Resource Routing: the Rails Default ----------------------------------- @@ -63,13 +65,13 @@ Resource routing allows you to quickly declare all of the common routes for a gi Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as `GET`, `POST`, `PATCH`, `PUT` and `DELETE`. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller. -When your Rails application receives an incoming request for +When your Rails application receives an incoming request for: ``` DELETE /photos/17 ``` -it asks the router to map it to a controller action. If the first matching route is +it asks the router to map it to a controller action. If the first matching route is: ```ruby resources :photos @@ -79,7 +81,7 @@ Rails would dispatch that request to the `destroy` method on the `photos` contro ### CRUD, Verbs, and Actions -In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as +In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as: ```ruby resources :photos @@ -87,7 +89,7 @@ resources :photos creates seven different routes in your application, all mapping to the `Photos` controller: -| HTTP Verb | Path | action | used for | +| HTTP Verb | Path | Action | Used for | | --------- | ---------------- | ------- | -------------------------------------------- | | GET | /photos | index | display a list of all photos | | GET | /photos/new | new | return an HTML form for creating a new photo | @@ -97,9 +99,11 @@ creates seven different routes in your application, all mapping to the `Photos` | PATCH/PUT | /photos/:id | update | update a specific photo | | DELETE | /photos/:id | destroy | delete a specific photo | +NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions. + NOTE: Rails routes are matched in the order they are specified, so if you have a `resources :photos` above a `get 'photos/poll'` the `show` action's route for the `resources` line will be matched before the `get` line. To fix this, move the `get` line **above** the `resources` line so that it is matched first. -### Paths and URLs +### Path and URL Helpers Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of `resources :photos`: @@ -110,8 +114,6 @@ Creating a resourceful route will also expose a number of helpers to the control Each of these helpers has a corresponding `_url` helper (such as `photos_url`) which returns the same path prefixed with the current host, port and path prefix. -NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions. - ### Defining Multiple Resources at the Same Time If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to `resources`: @@ -120,7 +122,7 @@ If you need to create routes for more than one resource, you can save a bit of t resources :photos, :books, :videos ``` -This works exactly the same as +This works exactly the same as: ```ruby resources :photos @@ -130,13 +132,13 @@ resources :videos ### Singular Resources -Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like `/profile` to always show the profile of the currently logged in user. In this case, you can use a singular resource to map `/profile` (rather than `/profile/:id`) to the `show` action. +Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like `/profile` to always show the profile of the currently logged in user. In this case, you can use a singular resource to map `/profile` (rather than `/profile/:id`) to the `show` action: ```ruby get 'profile', to: 'users#show' ``` -This resourceful route +This resourceful route: ```ruby resource :geocoder @@ -144,7 +146,7 @@ resource :geocoder creates six different routes in your application, all mapping to the `Geocoders` controller: -| HTTP Verb | Path | action | used for | +| HTTP Verb | Path | Action | Used for | | --------- | -------------- | ------- | --------------------------------------------- | | GET | /geocoder/new | new | return an HTML form for creating the geocoder | | POST | /geocoder | create | create the new geocoder | @@ -175,7 +177,7 @@ end This will create a number of routes for each of the `posts` and `comments` controller. For `Admin::PostsController`, Rails will create: -| HTTP Verb | Path | action | used for | +| HTTP Verb | Path | Action | Used for | | --------- | --------------------- | ------- | ------------------------- | | GET | /admin/posts | index | admin_posts_path | | GET | /admin/posts/new | new | new_admin_post_path | @@ -185,7 +187,7 @@ This will create a number of routes for each of the `posts` and `comments` contr | PATCH/PUT | /admin/posts/:id | update | admin_post_path(:id) | | DELETE | /admin/posts/:id | destroy | admin_post_path(:id) | -If you want to route `/posts` (without the prefix `/admin`) to `Admin::PostsController`, you could use +If you want to route `/posts` (without the prefix `/admin`) to `Admin::PostsController`, you could use: ```ruby scope module: 'admin' do @@ -193,13 +195,13 @@ scope module: 'admin' do end ``` -or, for a single case +or, for a single case: ```ruby resources :posts, module: 'admin' ``` -If you want to route `/admin/posts` to `PostsController` (without the `Admin::` module prefix), you could use +If you want to route `/admin/posts` to `PostsController` (without the `Admin::` module prefix), you could use: ```ruby scope '/admin' do @@ -207,7 +209,7 @@ scope '/admin' do end ``` -or, for a single case +or, for a single case: ```ruby resources :posts, path: '/admin/posts' @@ -215,7 +217,7 @@ resources :posts, path: '/admin/posts' In each of these cases, the named routes remain the same as if you did not use `scope`. In the last case, the following paths map to `PostsController`: -| HTTP Verb | Path | action | named helper | +| HTTP Verb | Path | Action | Named Helper | | --------- | --------------------- | ------- | ------------------- | | GET | /admin/posts | index | posts_path | | GET | /admin/posts/new | new | new_post_path | @@ -249,7 +251,7 @@ end In addition to the routes for magazines, this declaration will also route ads to an `AdsController`. The ad URLs require a magazine: -| HTTP Verb | Path | action | used for | +| HTTP Verb | Path | Action | Used for | | --------- | ------------------------------------ | ------- | -------------------------------------------------------------------------- | | GET | /magazines/:magazine_id/ads | index | display a list of all ads for a specific magazine | | GET | /magazines/:magazine_id/ads/new | new | return an HTML form for creating a new ad belonging to a specific magazine | @@ -273,7 +275,7 @@ resources :publishers do end ``` -Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as +Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as: ``` /publishers/1/magazines/2/photos/3 @@ -283,9 +285,94 @@ The corresponding route helper would be `publisher_magazine_photo_url`, requirin TIP: _Resources should never be nested more than 1 level deep._ +#### Shallow Nesting + +One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource, like this: + +```ruby +resources :posts do + resources :comments, only: [:index, :new, :create] +end +resources :comments, only: [:show, :edit, :update, :destroy] +``` + +This idea strikes a balance between descriptive routes and deep nesting. There exists shorthand syntax to achieve just that, via the `:shallow` option: + +```ruby +resources :posts do + resources :comments, shallow: true +end +``` + +This will generate the exact same routes as the first example. You can also specify the `:shallow` option in the parent resource, in which case all of the nested resources will be shallow: + +```ruby +resources :posts, shallow: true do + resources :comments + resources :quotes + resources :drafts +end +``` + +The `shallow` method of the DSL creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example: + +```ruby +shallow do + resources :posts do + resources :comments + resources :quotes + resources :drafts + end +end +``` + +There exists two options for `scope` to customize shallow routes. `:shallow_path` prefixes member paths with the specified parameter: + +```ruby +scope shallow_path: "sekret" do + resources :posts do + resources :comments, shallow: true + end +end +``` + +The comments resource here will have the following routes generated for it: + +| HTTP Verb | Path | Named Helper | +| --------- | -------------------------------------- | ------------------- | +| GET | /posts/:post_id/comments(.:format) | post_comments | +| POST | /posts/:post_id/comments(.:format) | post_comments | +| GET | /posts/:post_id/comments/new(.:format) | new_post_comment | +| GET | /sekret/comments/:id/edit(.:format) | edit_comment | +| GET | /sekret/comments/:id(.:format) | comment | +| PATCH/PUT | /sekret/comments/:id(.:format) | comment | +| DELETE | /sekret/comments/:id(.:format) | comment | + +The `:shallow_prefix` option adds the specified parameter to the named helpers: + +```ruby +scope shallow_prefix: "sekret" do + resources :posts do + resources :comments, shallow: true + end +end +``` + +The comments resource here will have the following routes generated for it: + +| HTTP Verb | Path | Named Helper | +| --------- | -------------------------------------- | ------------------- | +| GET | /posts/:post_id/comments(.:format) | post_comments | +| POST | /posts/:post_id/comments(.:format) | post_comments | +| GET | /posts/:post_id/comments/new(.:format) | new_post_comment | +| GET | /comments/:id/edit(.:format) | edit_sekret_comment | +| GET | /comments/:id(.:format) | sekret_comment | +| PATCH/PUT | /comments/:id(.:format) | sekret_comment | +| DELETE | /comments/:id(.:format) | sekret_comment | + ### Routing concerns -Routing Concerns allows you to declare common routes that can be reused inside others resources and routes. +Routing Concerns allows you to declare common routes that can be reused inside others resources and routes. To define a concern: ```ruby concern :commentable do @@ -297,7 +384,7 @@ concern :image_attachable do end ``` -These concerns can be used in resources to avoid code duplication and share behavior across routes. +These concerns can be used in resources to avoid code duplication and share behavior across routes: ```ruby resources :messages, concerns: :commentable @@ -305,6 +392,19 @@ resources :messages, concerns: :commentable resources :posts, concerns: [:commentable, :image_attachable] ``` +The above is equivalent to: + +```ruby +resources :messages do + resources :comments +end + +resources :posts do + resources :comments + resources :images, only: :index +end +``` + Also you can use them in any place that you want inside the routes, for example in a scope or namespace call: ```ruby @@ -323,7 +423,7 @@ resources :magazines do end ``` -When using `magazine_ad_path`, you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs. +When using `magazine_ad_path`, you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs: ```erb <%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %> @@ -415,9 +515,7 @@ end This will enable Rails to recognize paths such as `/comments/new/preview` with GET, and route to the `preview` action of `CommentsController`. It will also create the `preview_new_comment_url` and `preview_new_comment_path` route helpers. -#### A Note of Caution - -If you find yourself adding many extra actions to a resourceful route, it's time to stop and ask yourself whether you're disguising the presence of another resource. +TIP: If you find yourself adding many extra actions to a resourceful route, it's time to stop and ask yourself whether you're disguising the presence of another resource. Non-Resourceful Routes ---------------------- @@ -454,11 +552,11 @@ NOTE: You can't use `:namespace` or `:module` with a `:controller` path segment. get ':controller(/:action(/:id))', controller: /admin\/[^\/]+/ ``` -TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, `id: /[^\/]+/` allows anything except a slash. +TIP: By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, `id: /[^\/]+/` allows anything except a slash. ### Static Segments -You can specify static segments when creating a route: +You can specify static segments when creating a route by not prepending a colon to a fragment: ```ruby get ':controller/:action/:id/with_user/:user_id' @@ -496,7 +594,7 @@ Rails would match `photos/12` to the `show` action of `PhotosController`, and se ### Naming Routes -You can specify a name for any route using the `:as` option. +You can specify a name for any route using the `:as` option: ```ruby get 'exit', to: 'sessions#destroy', as: :logout @@ -526,7 +624,7 @@ You can match all verbs to a particular route using `via: :all`: match 'photos', to: 'photos#show', via: :all ``` -You should avoid routing all verbs to an action unless you have a good reason to, as routing both `GET` requests and `POST` requests to a single action has security implications. +NOTE: Routing both `GET` and `POST` requests to a single action has security implications. In general, you should avoid routing all verbs to an action unless you have a good reason to. ### Segment Constraints @@ -536,7 +634,7 @@ You can use the `:constraints` option to enforce a format for a dynamic segment: get 'photos/:id', to: 'photos#show', constraints: { id: /[A-Z]\d{5}/ } ``` -This route would match paths such as `/photos/A12345`. You can more succinctly express the same route this way: +This route would match paths such as `/photos/A12345`, but not `/photos/893`. You can more succinctly express the same route this way: ```ruby get 'photos/:id', to: 'photos#show', id: /[A-Z]\d{5}/ @@ -609,17 +707,17 @@ end Both the `matches?` method and the lambda gets the `request` object as an argument. -### Route Globbing +### Route Globbing and Wildcard Segments -Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example +Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example: ```ruby get 'photos/*other', to: 'photos#unknown' ``` -This route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`. +This route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`. The fragments prefixed with a star are called "wildcard segments". -Wildcard segments can occur anywhere in a route. For example, +Wildcard segments can occur anywhere in a route. For example: ```ruby get 'books/*section/:title', to: 'books#show' @@ -627,7 +725,7 @@ get 'books/*section/:title', to: 'books#show' would match `books/some/section/last-words-a-memoir` with `params[:section]` equals `'some/section'`, and `params[:title]` equals `'last-words-a-memoir'`. -Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example, +Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example: ```ruby get '*a/foo/*b', to: 'test#index' @@ -635,12 +733,6 @@ get '*a/foo/*b', to: 'test#index' would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'`, and `params[:b]` equals `'bar/baz'`. -NOTE: Starting from Rails 3.1, wildcard routes will always match the optional format segment by default. For example if you have this route: - -```ruby -get '*pages', to: 'pages#show' -``` - NOTE: By requesting `'/foo/bar.json'`, your `params[:pages]` will be equals to `'foo/bar'` with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `format: false` like this: ```ruby @@ -680,7 +772,7 @@ In all of these cases, if you don't provide the leading host (`http://www.exampl ### Routing to Rack Applications -Instead of a String, like `'posts#index'`, which corresponds to the `index` action in the `PostsController`, you can specify any <a href="rails_on_rack.html">Rack application</a> as the endpoint for a matcher. +Instead of a String like `'posts#index'`, which corresponds to the `index` action in the `PostsController`, you can specify any <a href="rails_on_rack.html">Rack application</a> as the endpoint for a matcher: ```ruby match '/application.js', to: Sprockets, via: :all @@ -705,7 +797,7 @@ NOTE: The `root` route only routes `GET` requests to the action. ### Unicode character routes -You can specify unicode character routes directly. For example +You can specify unicode character routes directly. For example: ```ruby get 'こんにちは', to: 'welcome#index' @@ -726,7 +818,7 @@ resources :photos, controller: 'images' will recognize incoming paths beginning with `/photos` but route to the `Images` controller: -| HTTP Verb | Path | action | named helper | +| HTTP Verb | Path | Action | Named Helper | | --------- | ---------------- | ------- | -------------------- | | GET | /photos | index | photos_path | | GET | /photos/new | new | new_photo_path | @@ -771,7 +863,7 @@ resources :photos, as: 'images' will recognize incoming paths beginning with `/photos` and route the requests to `PhotosController`, but use the value of the :as option to name the helpers. -| HTTP Verb | Path | action | named helper | +| HTTP Verb | Path | Action | Named Helper | | --------- | ---------------- | ------- | -------------------- | | GET | /photos | index | images_path | | GET | /photos/new | new | new_image_path | @@ -789,7 +881,7 @@ The `:path_names` option lets you override the automatically-generated "new" and resources :photos, path_names: { new: 'make', edit: 'change' } ``` -This would cause the routing to recognize paths such as +This would cause the routing to recognize paths such as: ``` /photos/make @@ -808,7 +900,7 @@ end ### Prefixing the Named Route Helpers -You can use the `:as` option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope. +You can use the `:as` option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope. For example: ```ruby scope 'admin' do @@ -876,7 +968,7 @@ end Rails now creates routes to the `CategoriesController`. -| HTTP Verb | Path | action | used for | +| HTTP Verb | Path | Action | Used for | | --------- | -------------------------- | ------- | ----------------------- | | GET | /kategorien | index | categories_path | | GET | /kategorien/neu | new | new_category_path | @@ -888,7 +980,7 @@ Rails now creates routes to the `CategoriesController`. ### Overriding the Singular Form -If you want to define the singular form of a resource, you should add additional rules to the `Inflector`. +If you want to define the singular form of a resource, you should add additional rules to the `Inflector`: ```ruby ActiveSupport::Inflector.inflections do |inflect| @@ -898,7 +990,7 @@ end ### Using `:as` in Nested Resources -The `:as` option overrides the automatically-generated name for the resource in nested route helpers. For example, +The `:as` option overrides the automatically-generated name for the resource in nested route helpers. For example: ```ruby resources :magazines do @@ -913,7 +1005,7 @@ Inspecting and Testing Routes Rails offers facilities for inspecting and testing your routes. -### Seeing Existing Routes +### Listing Existing Routes To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `rake routes` command in your terminal to produce the same output. @@ -951,7 +1043,7 @@ Routes should be included in your testing strategy (just like the rest of your a #### The `assert_generates` Assertion -`assert_generates` asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. +`assert_generates` asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. For example: ```ruby assert_generates '/photos/1', { controller: 'photos', action: 'show', id: '1' } @@ -960,7 +1052,7 @@ assert_generates '/about', controller: 'pages', action: 'about' #### The `assert_recognizes` Assertion -`assert_recognizes` is the inverse of `assert_generates`. It asserts that a given path is recognized and routes it to a particular spot in your application. +`assert_recognizes` is the inverse of `assert_generates`. It asserts that a given path is recognized and routes it to a particular spot in your application. For example: ```ruby assert_recognizes({ controller: 'photos', action: 'show', id: '1' }, '/photos/1') @@ -974,7 +1066,7 @@ assert_recognizes({ controller: 'photos', action: 'create' }, { path: 'photos', #### The `assert_routing` Assertion -The `assert_routing` assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of `assert_generates` and `assert_recognizes`. +The `assert_routing` assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of `assert_generates` and `assert_recognizes`: ```ruby assert_routing({ path: 'photos', method: :post }, { controller: 'photos', action: 'create' }) diff --git a/guides/source/ruby_on_rails_guides_guidelines.md b/guides/source/ruby_on_rails_guides_guidelines.md index 6e3173cdb4..a78711f4b2 100644 --- a/guides/source/ruby_on_rails_guides_guidelines.md +++ b/guides/source/ruby_on_rails_guides_guidelines.md @@ -5,6 +5,9 @@ This guide documents guidelines for writing Ruby on Rails Guides. This guide fol After reading this guide, you will know: +* About the conventions to be used in Rails documentation. +* How to generate guides locally. + -------------------------------------------------------------------------------- Markdown @@ -62,7 +65,7 @@ HTML Guides ### Generation -To generate all the guides, just `cd` into the **`guides`** directory and execute: +To generate all the guides, just `cd` into the **`guides`** directory, run `bundle install` and execute: ``` bundle exec rake guides:generate @@ -74,8 +77,6 @@ or bundle exec rake guides:generate:html ``` -(You may need to run `bundle install` first to install the required gems.) - To process `my_guide.md` and nothing else use the `ONLY` environment variable: ``` diff --git a/guides/source/security.md b/guides/source/security.md index 6c32a8ff5b..532a1ae5cc 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -688,7 +688,7 @@ NOTE: _When sanitizing, protecting or verifying something, whitelists over black A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _prefer to use whitelist approaches_: -* Use before_filter only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions. +* Use before_action only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions. * Use attr_accessible instead of attr_protected. See the mass-assignment section for details * Allow <strong> instead of removing <script> against Cross-Site Scripting (XSS). See below for details. * Don't try to correct user input by blacklists: diff --git a/guides/source/testing.md b/guides/source/testing.md index 9ce94f4c53..a9bce04522 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -6,9 +6,9 @@ application. After reading this guide, you will know: -* Understand Rails testing terminology. -* Write unit, functional, and integration tests for your application. -* Identify other popular testing approaches and plugins. +* Rails testing terminology. +* How to write unit, functional, and integration tests for your application. +* Other popular testing approaches and plugins. -------------------------------------------------------------------------------- diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md index 26e3403ff9..0f5acfba3c 100644 --- a/guides/source/working_with_javascript_in_rails.md +++ b/guides/source/working_with_javascript_in_rails.md @@ -7,10 +7,10 @@ ease! After reading this guide, you will know: -* Quick introduction to Ajax. +* The basics of Ajax. * Unobtrusive JavaScript. * How Rails' built-in helpers assist you. -* Handling Ajax on the server side. +* How to handle Ajax on the server side. * The Turbolinks gem. ------------------------------------------------------------------------------- |