diff options
Diffstat (limited to 'guides')
42 files changed, 454 insertions, 315 deletions
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md index 37257baeba..afa695d445 100644 --- a/guides/CHANGELOG.md +++ b/guides/CHANGELOG.md @@ -1,5 +1,5 @@ * Removed repetitive th tags. Instead of them added one th tag with a colspan attribute. - + *Sıtkı Bağdat* Please check [4-0-stable](https://github.com/rails/rails/blob/4-0-stable/guides/CHANGELOG.md) for previous changes. diff --git a/guides/assets/stylesheets/main.css b/guides/assets/stylesheets/main.css index dd029e6314..898f9ff05b 100644 --- a/guides/assets/stylesheets/main.css +++ b/guides/assets/stylesheets/main.css @@ -129,6 +129,7 @@ body { font-family: Helvetica, Arial, Sans-Serif; text-decoration: none; vertical-align: middle; + cursor: pointer; } .red-button:active { border-top: none; @@ -244,7 +245,7 @@ body { #subCol { position: absolute; z-index: 0; - top: 0; + top: 21px; right: 0; background: #FFF; padding: 1em 1.5em 1em 1.25em; diff --git a/guides/assets/stylesheets/print.css b/guides/assets/stylesheets/print.css index 628da105d4..bdc8ec948d 100644 --- a/guides/assets/stylesheets/print.css +++ b/guides/assets/stylesheets/print.css @@ -36,7 +36,7 @@ hr { } h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; } -code { font:.9em "Courier New", Monaco, Courier, monospace; } +code { font:.9em "Courier New", Monaco, Courier, monospace; display:inline} img { float:left; margin:1.5em 1.5em 1.5em 0; } a img { border:none; } diff --git a/guides/bug_report_templates/active_record_gem.rb b/guides/bug_report_templates/active_record_gem.rb index 2e604bec47..a8868a1877 100644 --- a/guides/bug_report_templates/active_record_gem.rb +++ b/guides/bug_report_templates/active_record_gem.rb @@ -1,5 +1,5 @@ # Activate the gem you are reporting the issue against. -gem 'activerecord', '3.2.13' +gem 'activerecord', '4.0.0' require 'active_record' require 'minitest/autorun' require 'logger' diff --git a/guides/code/getting_started/Gemfile.lock b/guides/code/getting_started/Gemfile.lock index 888a6b30e2..2d5c50ef5c 100644 --- a/guides/code/getting_started/Gemfile.lock +++ b/guides/code/getting_started/Gemfile.lock @@ -1,135 +1,107 @@ -GIT - remote: git://github.com/rails/activerecord-deprecated_finders.git - revision: 2e7b35d7948cefb2bba96438873d7f7bb1961a03 - specs: - activerecord-deprecated_finders (0.0.2) - -GIT - remote: git://github.com/rails/arel.git - revision: 38d0a222e275d917a2c1d093b24457bafb600a00 - specs: - arel (3.0.2.20120819075748) - -GIT - remote: git://github.com/rails/coffee-rails.git - revision: 052634e6d02d4800d7b021201cc8d5829775b3cd - specs: - coffee-rails (4.0.0.beta) - coffee-script (>= 2.2.0) - railties (>= 4.0.0.beta, < 5.0) - -GIT - remote: git://github.com/rails/sass-rails.git - revision: ae8138a89cac397c0df903dd533e2862902ce8f5 - specs: - sass-rails (4.0.0.beta) - railties (>= 4.0.0.beta, < 5.0) - sass (>= 3.1.10) - sprockets-rails (~> 2.0.0.rc0) - tilt (~> 1.3) - -GIT - remote: git://github.com/rails/sprockets-rails.git - revision: 09917104fdb42245fe369612a7b0e3d77e1ba763 - specs: - sprockets-rails (2.0.0.rc1) - actionpack (>= 3.0) - activesupport (>= 3.0) - sprockets (~> 2.8) - -PATH - remote: /Users/steve/src/rails +GEM + remote: https://rubygems.org/ specs: - actionmailer (4.0.0.beta) - actionpack (= 4.0.0.beta) + actionmailer (4.0.0) + actionpack (= 4.0.0) mail (~> 2.5.3) - actionpack (4.0.0.beta) - activesupport (= 4.0.0.beta) + actionpack (4.0.0) + activesupport (= 4.0.0) builder (~> 3.1.0) erubis (~> 2.7.0) - rack (~> 1.4.3) - rack-test (~> 0.6.1) - activemodel (4.0.0.beta) - activesupport (= 4.0.0.beta) + rack (~> 1.5.2) + rack-test (~> 0.6.2) + activemodel (4.0.0) + activesupport (= 4.0.0) builder (~> 3.1.0) - activerecord (4.0.0.beta) - activemodel (= 4.0.0.beta) - activerecord-deprecated_finders (= 0.0.2) - activesupport (= 4.0.0.beta) - arel (~> 3.0.2) - activesupport (4.0.0.beta) - i18n (~> 0.6) - minitest (~> 4.1) + activerecord (4.0.0) + activemodel (= 4.0.0) + activerecord-deprecated_finders (~> 1.0.2) + activesupport (= 4.0.0) + arel (~> 4.0.0) + activerecord-deprecated_finders (1.0.3) + activesupport (4.0.0) + i18n (~> 0.6, >= 0.6.4) + minitest (~> 4.2) multi_json (~> 1.3) thread_safe (~> 0.1) - tzinfo (~> 0.3.33) - rails (4.0.0.beta) - actionmailer (= 4.0.0.beta) - actionpack (= 4.0.0.beta) - activerecord (= 4.0.0.beta) - activesupport (= 4.0.0.beta) - bundler (>= 1.2.2, < 2.0) - railties (= 4.0.0.beta) - sprockets-rails (~> 2.0.0.rc1) - railties (4.0.0.beta) - actionpack (= 4.0.0.beta) - activesupport (= 4.0.0.beta) - rake (>= 0.8.7) - rdoc (~> 3.4) - thor (>= 0.15.4, < 2.0) - -GEM - remote: https://rubygems.org/ - specs: - atomic (1.0.1) + tzinfo (~> 0.3.37) + arel (4.0.0) + atomic (1.1.10) builder (3.1.4) + coffee-rails (4.0.0) + coffee-script (>= 2.2.0) + railties (>= 4.0.0.beta, < 5.0) coffee-script (2.2.0) coffee-script-source execjs - coffee-script-source (1.4.0) + coffee-script-source (1.6.3) erubis (2.7.0) execjs (1.4.0) multi_json (~> 1.0) - hike (1.2.1) - i18n (0.6.1) - jbuilder (1.3.0) + hike (1.2.3) + i18n (0.6.4) + jbuilder (1.4.2) activesupport (>= 3.0.0) - jquery-rails (2.2.0) + multi_json (>= 1.2.0) + jquery-rails (3.0.2) railties (>= 3.0, < 5.0) thor (>= 0.14, < 2.0) - json (1.7.6) - mail (2.5.3) - i18n (>= 0.4.0) + json (1.8.0) + mail (2.5.4) mime-types (~> 1.16) treetop (~> 1.4.8) - mime-types (1.19) - minitest (4.4.0) - multi_json (1.5.0) + mime-types (1.23) + minitest (4.7.5) + multi_json (1.7.7) polyglot (0.3.3) - rack (1.4.4) + rack (1.5.2) rack-test (0.6.2) rack (>= 1.0) - rake (10.0.3) - rdoc (3.12) + rails (4.0.0) + actionmailer (= 4.0.0) + actionpack (= 4.0.0) + activerecord (= 4.0.0) + activesupport (= 4.0.0) + bundler (>= 1.3.0, < 2.0) + railties (= 4.0.0) + sprockets-rails (~> 2.0.0) + railties (4.0.0) + actionpack (= 4.0.0) + activesupport (= 4.0.0) + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (10.1.0) + rdoc (3.12.2) json (~> 1.4) - sass (3.2.5) - sprockets (2.8.2) + sass (3.2.9) + sass-rails (4.0.0) + railties (>= 4.0.0.beta, < 5.0) + sass (>= 3.1.10) + sprockets-rails (~> 2.0.0) + sdoc (0.3.20) + json (>= 1.1.3) + rdoc (~> 3.10) + sprockets (2.10.0) hike (~> 1.2) multi_json (~> 1.0) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) + sprockets-rails (2.0.0) + actionpack (>= 3.0) + activesupport (>= 3.0) + sprockets (~> 2.8) sqlite3 (1.3.7) - thor (0.16.0) + thor (0.18.1) thread_safe (0.1.0) atomic - tilt (1.3.3) - treetop (1.4.12) + tilt (1.4.1) + treetop (1.4.14) polyglot polyglot (>= 0.3.1) - turbolinks (1.0.0) + turbolinks (1.2.0) coffee-rails - tzinfo (0.3.35) - uglifier (1.3.0) + tzinfo (0.3.37) + uglifier (2.1.1) execjs (>= 0.3.0) multi_json (~> 1.0, >= 1.0.2) @@ -137,14 +109,12 @@ PLATFORMS ruby DEPENDENCIES - activerecord-deprecated_finders! - arel! - coffee-rails! - jbuilder (~> 1.0.1) + coffee-rails + jbuilder (~> 1.2) jquery-rails - rails! - sass-rails! - sprockets-rails! + rails (= 4.0.0) + sass-rails + sdoc sqlite3 turbolinks uglifier (>= 1.0.3) diff --git a/guides/code/getting_started/app/controllers/comments_controller.rb b/guides/code/getting_started/app/controllers/comments_controller.rb index 0e3d2a6dde..b2d9bcdf7f 100644 --- a/guides/code/getting_started/app/controllers/comments_controller.rb +++ b/guides/code/getting_started/app/controllers/comments_controller.rb @@ -4,7 +4,7 @@ class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) - @comment = @post.comments.create(params[:comment].permit(:commenter, :body)) + @comment = @post.comments.create(comment_params) redirect_to post_path(@post) end @@ -14,4 +14,10 @@ class CommentsController < ApplicationController @comment.destroy redirect_to post_path(@post) end + + private + + def comment_params + params.require(:comment).permit(:commenter, :body) + end end diff --git a/guides/code/getting_started/app/controllers/posts_controller.rb b/guides/code/getting_started/app/controllers/posts_controller.rb index 6aa1409170..02689ad67b 100644 --- a/guides/code/getting_started/app/controllers/posts_controller.rb +++ b/guides/code/getting_started/app/controllers/posts_controller.rb @@ -17,7 +17,7 @@ class PostsController < ApplicationController def update @post = Post.find(params[:id]) - if @post.update(params[:post].permit(:title, :text)) + if @post.update(post_params) redirect_to action: :show, id: @post.id else render 'edit' @@ -29,7 +29,7 @@ class PostsController < ApplicationController end def create - @post = Post.new(params[:post].permit(:title, :text)) + @post = Post.new(post_params) if @post.save redirect_to action: :show, id: @post.id @@ -44,4 +44,10 @@ class PostsController < ApplicationController redirect_to action: :index end + + private + + def post_params + params.require(:post).permit(:title, :text) + end end diff --git a/guides/code/getting_started/app/views/posts/_form.html.erb b/guides/code/getting_started/app/views/posts/_form.html.erb index c9fb74af9c..f2f83585e1 100644 --- a/guides/code/getting_started/app/views/posts/_form.html.erb +++ b/guides/code/getting_started/app/views/posts/_form.html.erb @@ -1,6 +1,6 @@ <%= form_for @post do |f| %> <% if @post.errors.any? %> - <div id="errorExplanation"> + <div id="error_explanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> @@ -14,12 +14,12 @@ <%= f.label :title %><br> <%= f.text_field :title %> </p> - + <p> <%= f.label :text %><br> <%= f.text_area :text %> </p> - + <p> <%= f.submit %> </p> diff --git a/guides/code/getting_started/app/views/welcome/index.html.erb b/guides/code/getting_started/app/views/welcome/index.html.erb index 738e12d7dc..56be8dd3cc 100644 --- a/guides/code/getting_started/app/views/welcome/index.html.erb +++ b/guides/code/getting_started/app/views/welcome/index.html.erb @@ -1,3 +1,4 @@ <h1>Hello, Rails!</h1> <%= link_to "My Blog", controller: "posts" %> +<%= link_to "New Post", new_post_path %> diff --git a/guides/code/getting_started/config/environments/development.rb b/guides/code/getting_started/config/environments/development.rb index d169e9452c..7e5692b08b 100644 --- a/guides/code/getting_started/config/environments/development.rb +++ b/guides/code/getting_started/config/environments/development.rb @@ -22,7 +22,7 @@ Blog::Application.configure do # Only use best-standards-support built into browsers. config.action_dispatch.best_standards_support = :builtin - # Raise an error on page load if there are pending migrations + # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md index e036860de2..dc4d942671 100644 --- a/guides/source/3_2_release_notes.md +++ b/guides/source/3_2_release_notes.md @@ -240,11 +240,11 @@ Action Pack In the example above, Posts controller will no longer automatically look up for a posts layout. If you need this functionality you could either remove `layout "application"` from `ApplicationController` or explicitly set it to `nil` in `PostsController`. -* Deprecated `ActionController::UnknownAction` in favour of `AbstractController::ActionNotFound`. +* Deprecated `ActionController::UnknownAction` in favor of `AbstractController::ActionNotFound`. -* Deprecated `ActionController::DoubleRenderError` in favour of `AbstractController::DoubleRenderError`. +* Deprecated `ActionController::DoubleRenderError` in favor of `AbstractController::DoubleRenderError`. -* Deprecated `method_missing` in favour of `action_missing` for missing actions. +* Deprecated `method_missing` in favor of `action_missing` for missing actions. * Deprecated `ActionController#rescue_action`, `ActionController#initialize_template_class` and `ActionController#assign_shortcuts`. diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 6ebeeed0bf..66e26c63cb 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -52,7 +52,7 @@ Major Features TODO. Give a list and then talk about each of them briefly. We can point to relevant code commits or documentation from these sections. -![Rails 4.0](images/rails4_features.png) +[![Rails 4.0](images/rails4_features.png)](http://guides.rubyonrails.org/images/rails4_features.png) Extraction of features to gems --------------------------- @@ -89,6 +89,10 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railt * Threadsafe on by default +* Ability to use a custom builder by passing `--builder` (or `-b`) to + `rails new` has been removed. Consider using application templates + instead. ([Pull Request](https://github.com/rails/rails/pull/9401)) + ### Deprecations * `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded. diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index a50961a0c7..9210c40c17 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -10,10 +10,13 @@ </p> <% else %> <p> - These are the new guides for Rails 3.2 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>. + These are the new guides for Rails 4.0 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>. These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together. </p> <% end %> <p> + The guides for Rails 3.2.x are available at <a href="http://guides.rubyonrails.org/v3.2.13/">http://guides.rubyonrails.org/v3.2.13/</a>. +</p> +<p> The guides for Rails 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>. </p> diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index 2701f5bb72..f2abd833aa 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -129,7 +129,7 @@ Note that the `params` hash is actually an instance of `ActiveSupport::HashWithI ### JSON parameters -If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. Rails will automatically convert your parameters into the `params` hash, which you can access as you would normally. +If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. If the "Content-Type" header of your request is set to "application/json", Rails will automatically convert your parameters into the `params` hash, which you can access as you would normally. So for example, if you are sending this JSON content: @@ -160,7 +160,7 @@ NOTE: Support for parsing XML parameters has been extracted into a gem named `ac The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the `:status` parameter in a "pretty" URL: ```ruby -match '/clients/:status' => 'clients#index', foo: 'bar' +get '/clients/:status' => 'clients#index', foo: 'bar' ``` In this case, when a user opens the URL `/clients/active`, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar" just like it was passed in the query string. In the same way `params[:action]` will contain "index". @@ -346,7 +346,7 @@ Your application has a session for each user in which you can store small amount All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure). -For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). +For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof. And it is also encrypted so anyone with access to it can't read its contents. (Rails will not accept it if it has been edited). The CookieStore can store around 4kB of data — much less than the others — but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. @@ -410,7 +410,7 @@ class ApplicationController < ActionController::Base # logging out removes it. def current_user @_current_user ||= session[:current_user_id] && - User.find_by_id(session[:current_user_id]) + User.find_by(id: session[:current_user_id]) end end ``` diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index d1dd231cf6..87a08e8661 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -216,6 +216,11 @@ Action Mailer makes it very easy to add attachments. attachments['filename.jpg'] = File.read('/path/to/filename.jpg') ``` + When the `mail` method will be triggered, it will send a multipart email with + an attachment, properly nested with the top level being `multipart/mixed` and + the first part being a `multipart/alternative` containing the plain text and + HTML email messages. + NOTE: Mail will automatically Base64 encode an attachment. If you want something different, encode your content and pass in the encoded content and encoding in a `Hash` to the `attachments` method. @@ -451,26 +456,6 @@ with the HTML and text versions setup as different parts. The order of the parts getting inserted is determined by the `:parts_order` inside of the `ActionMailer::Base.default` method. -### Sending Emails with Attachments - -Attachments can be added by using the `attachments` method: - -```ruby -class UserMailer < ActionMailer::Base - def welcome_email(user) - @user = user - @url = user_url(@user) - attachments['terms.pdf'] = File.read('/path/terms.pdf') - mail(to: @user.email, - subject: 'Please see the Terms and Conditions attached') - end -end -``` - -The above will send a multipart email with an attachment, properly nested with -the top level being `multipart/mixed` and the first part being a -`multipart/alternative` containing the plain text and HTML email messages. - ### Sending Emails with Dynamic Delivery Options If you wish to override the default delivery options (e.g. SMTP credentials) @@ -532,7 +517,7 @@ method. Here's an example: ```ruby class UserMailer < ActionMailer::Base def receive(email) - page = Page.find_by_address(email.to.first) + page = Page.find_by(address: email.to.first) page.emails.create( subject: email.subject, body: email.body diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md index dea1ddef71..75f2989f5b 100644 --- a/guides/source/action_view_overview.md +++ b/guides/source/action_view_overview.md @@ -941,9 +941,9 @@ Creates a form and a scope around a specific model object that is used as a base ```html+erb <%= form_for @post do |f| %> <%= f.label :title, 'Title' %>: - <%= f.text_field :title %><br /> + <%= f.text_field :title %><br> <%= f.label :body, 'Body' %>: - <%= f.text_area :body %><br /> + <%= f.text_area :body %><br> <% end %> ``` @@ -1006,6 +1006,24 @@ text_field(:post, :title) # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" /> ``` +#### email_field + +Returns an input tag of the "email" type tailored for accessing a specified attribute. + +```ruby +email_field(:user, :email) +# => <input type="email" id="user_email" name="user[email]" value="#{@user.email}" /> +``` + +#### url_field + +Returns an input tag of the "url" type tailored for accessing a specified attribute. + +```ruby +url_field(:user, :url) +# => <input type="url" id="user_url" name="user[url]" value="#{@user.url}" /> +``` + ### FormOptionsHelper Provides a number of methods for turning different kinds of containers into a set of option tags. @@ -1090,7 +1108,7 @@ Example object structure for use with this method: ```ruby class Post < ActiveRecord::Base - has_and_belongs_to_many :author + has_and_belongs_to_many :authors end class Author < ActiveRecord::Base @@ -1230,6 +1248,14 @@ Return select and option tags for the given object and method, using `time_zone_ time_zone_select( "user", "time_zone") ``` +#### date_field + +Returns an input tag of the "date" type tailored for accessing a specified attribute. + +```ruby +date_field("user", "dob") +``` + ### FormTagHelper Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually. @@ -1364,6 +1390,33 @@ text_field_tag 'name' # => <input id="name" name="name" type="text" /> ``` +#### email_field_tag + +Creates a standard input field of email type. + +```ruby +email_field_tag 'email' +# => <input id="email" name="email" type="email" /> +``` + +#### url_field_tag + +Creates a standard input field of url type. + +```ruby +url_field_tag 'url' +# => <input id="url" name="url" type="url" /> +``` + +#### date_field_tag + +Creates a standard input field of date type. + +```ruby +date_field_tag "dob" +# => <input id="dob" name="dob" type="date" /> +``` + ### JavaScriptHelper Provides functionality for working with JavaScript in your views. @@ -1439,7 +1492,7 @@ number_to_human_size(1234567) # => 1.2 MB Formats a number as a percentage string. ```ruby -number_to_percentage(100, :precision => 0) # => 100% +number_to_percentage(100, precision: 0) # => 100% ``` #### number_to_phone diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index 1f25c6ae95..556c2544ff 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -105,7 +105,7 @@ depending on the purpose of these columns. Migrations](migrations.html) to create your tables, this column will be automatically created. -There are also some optional column names that will create additional features +There are also some optional column names that will add additional features to Active Record instances: * `created_at` - Automatically gets set to the current date and time when the @@ -253,7 +253,7 @@ user = User.first ```ruby # return the first user named David -david = User.find_by_name('David') +david = User.find_by(name: 'David') ``` ```ruby @@ -270,7 +270,7 @@ 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 = User.find_by(name: 'David') user.name = 'Dave' user.save ``` @@ -279,7 +279,7 @@ A shorthand for this is to use a hash mapping attribute names to the desired value, like so: ```ruby -user = User.find_by_name('David') +user = User.find_by(name: 'David') user.update(name: 'Dave') ``` @@ -297,7 +297,7 @@ Likewise, once retrieved an Active Record object can be destroyed which removes it from the database. ```ruby -user = User.find_by_name('David') +user = User.find_by(name: 'David') user.destroy ``` @@ -343,7 +343,7 @@ Migrations Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any -database that Active Record support using `rake`. Here's a migration that +database that Active Record supports using `rake`. Here's a migration that creates a table: ```ruby diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index bb42fab101..2e70e64b39 100644 --- a/guides/source/active_record_callbacks.md +++ b/guides/source/active_record_callbacks.md @@ -167,6 +167,7 @@ Additionally, the `after_find` callback is triggered by the following finder met * `all` * `first` * `find` +* `find_by` * `find_by_*` * `find_by_*!` * `find_by_sql` @@ -342,7 +343,7 @@ By using the `after_commit` callback we can account for this case. ```ruby class PictureFile < ActiveRecord::Base - after_commit :delete_picture_file_from_disk, :on => [:destroy] + after_commit :delete_picture_file_from_disk, on: [:destroy] def delete_picture_file_from_disk if File.exist?(filepath) diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 2555927d15..18a5342a2f 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -58,6 +58,7 @@ The methods are: * `bind` * `create_with` +* `distinct` * `eager_load` * `extending` * `from` @@ -76,7 +77,6 @@ The methods are: * `reorder` * `reverse_order` * `select` -* `distinct` * `uniq` * `where` @@ -711,7 +711,7 @@ Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all You can additionally unscope specific where clauses. For example: ```ruby -Post.where(:id => 10).limit(1).unscope(where: :id, :limit).order('id DESC') = Post.order('id DESC') +Post.where(id: 10).limit(1).unscope(:where, :limit).order('id DESC') = Post.order('id DESC') ``` ### `only` @@ -1210,9 +1210,7 @@ class User < ActiveRecord::Base scope :active, -> { where state: 'active' } scope :inactive, -> { where state: 'inactive' } end -``` -```ruby User.active.inactive # => SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive' ``` diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index 37790c62b1..3bfc600e7c 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -120,8 +120,8 @@ database only if the object is valid: * `update!` The bang versions (e.g. `save!`) raise an exception if the record is invalid. -The non-bang versions don't: `save` and `update` return `false`, -`create` and `update` just return the objects. +The non-bang versions don't, `save` and `update` return `false`, +`create` just return the objects. ### Skipping Validations diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md index 38dbfd3152..969596f470 100644 --- a/guides/source/active_support_instrumentation.md +++ b/guides/source/active_support_instrumentation.md @@ -39,7 +39,7 @@ Action Controller ```ruby { - key: 'posts/1-dasboard-view' + key: 'posts/1-dashboard-view' } ``` @@ -51,7 +51,7 @@ Action Controller ```ruby { - key: 'posts/1-dasboard-view' + key: 'posts/1-dashboard-view' } ``` @@ -63,7 +63,7 @@ Action Controller ```ruby { - key: 'posts/1-dasboard-view' + key: 'posts/1-dashboard-view' } ``` @@ -75,7 +75,7 @@ Action Controller ```ruby { - key: 'posts/1-dasboard-view' + key: 'posts/1-dashboard-view' } ``` diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index b68c24acfd..a6e3d3b0ac 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -69,12 +69,12 @@ Rails' old strategy was to append a date-based query string to every asset linke The query string strategy has several disadvantages: -1. **Not all caches will reliably cache content where the filename only differs by query parameters**<br /> +1. **Not all caches will reliably cache content where the filename only differs by query parameters**<br> [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation. -2. **The file name can change between nodes in multi-server environments.**<br /> +2. **The file name can change between nodes in multi-server environments.**<br> The default query string in Rails 2.x is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request. -3. **Too much cache invalidation**<br /> +3. **Too much cache invalidation**<br> When static assets are deployed with each new release of code, the mtime(time of last modification) of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. Fingerprinting fixes these problems by avoiding query strings, and by ensuring that filenames are consistent based on their content. diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index d7277b487f..884aa6a9ea 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -781,7 +781,7 @@ The `create_association` method returns a new object of the associated type. Thi ##### `create_association!(attributes = {})` -Does the same as <tt>create_association</tt> above, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid. +Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid. #### Options for `belongs_to` @@ -1083,7 +1083,7 @@ The `create_association` method returns a new object of the associated type. Thi ##### `create_association!(attributes = {})` -Does the same as <tt>create_association</tt> above, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid. +Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid. #### Options for `has_one` @@ -1443,7 +1443,7 @@ The `collection.create` method returns a new object of the associated type. This ##### `collection.create!(attributes = {})` -Does the same as <tt>collection.create</tt> above, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid. +Does the same as `collection.create` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid. #### Options for `has_many` @@ -1736,15 +1736,15 @@ If you want to make sure that, upon insertion, all of the records in the persisted association are distinct (so that you can be sure that when you inspect the association that you will never find duplicate records), you should add a unique index on the table itself. For example, if you have a table named -``person_posts`` and you want to make sure all the posts are unique, you could +`person_posts` and you want to make sure all the posts are unique, you could add the following in a migration: ```ruby -add_index :person_posts, :post, :unique => true +add_index :person_posts, :post, unique: true ``` -Note that checking for uniqueness using something like ``include?`` is subject -to race conditions. Do not attempt to use ``include?`` to enforce distinctness +Note that checking for uniqueness using something like `include?` is subject +to race conditions. Do not attempt to use `include?` to enforce distinctness in an association. For instance, using the post example from above, the following code would be racy because multiple users could be attempting this at the same time: @@ -1936,7 +1936,7 @@ The `collection.create` method returns a new object of the associated type. This ##### `collection.create!(attributes = {})` -Does the same as <tt>collection.create</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt> if the record is invalid. +Does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid` if the record is invalid. #### Options for `has_and_belongs_to_many` @@ -2171,7 +2171,7 @@ You're not limited to the functionality that Rails automatically builds into ass class Customer < ActiveRecord::Base has_many :orders do def find_by_order_prefix(order_number) - find_by_region_id(order_number[0..2]) + find_by(region_id: order_number[0..2]) end end end @@ -2199,4 +2199,4 @@ Extensions can refer to the internals of the association proxy using these three * `proxy_association.owner` returns the object that the association is a part of. * `proxy_association.reflection` returns the reflection object that describes the association. -* `proxy_association.target` returns the associated object for `belongs_to` or `has_one`, or the collection of associated objects for `has_many` or `has_and_belongs_to_many`.
\ No newline at end of file +* `proxy_association.target` returns the associated object for `belongs_to` or `has_one`, or the collection of associated objects for `has_many` or `has_and_belongs_to_many`. diff --git a/guides/source/command_line.md b/guides/source/command_line.md index e0b44bbf93..218b4dd39a 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -27,6 +27,8 @@ There are a few commands that are absolutely critical to your everyday usage of * `rails dbconsole` * `rails new app_name` +All commands can run with ```-h or --help``` to list more information. + Let's create a simple Rails application to step through each of these commands in context. ### `rails new` @@ -64,7 +66,7 @@ With no further work, `rails server` will run our new shiny Rails app: $ cd commandsapp $ rails server => Booting WEBrick -=> Rails 3.2.3 application starting in development on http://0.0.0.0:3000 +=> Rails 4.0.0 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2012-05-28 00:39:41] INFO WEBrick 1.3.1 @@ -289,7 +291,7 @@ If you wish to test out some code without changing any data, you can do that by ```bash $ rails console --sandbox -Loading development environment in sandbox (Rails 3.2.3) +Loading development environment in sandbox (Rails 4.0.0) Any modifications you make will be rolled back on exit irb(main):001:0> ``` @@ -348,6 +350,9 @@ Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'mak You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need. +To get the full backtrace for running rake task you can pass the option +```--trace``` to command line, for example ```rake db:create --trace```. + ```bash $ rake --tasks rake about # List versions of all Rails frameworks and the environment @@ -361,6 +366,7 @@ rake middleware # Prints out your Rack middleware stack rake tmp:clear # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear) rake tmp:create # Creates tmp directories for sessions, cache, sockets, and pids ``` +INFO: You can also use ```rake -T``` to get the list of tasks. ### `about` @@ -372,12 +378,12 @@ About your application's environment Ruby version 1.9.3 (x86_64-linux) RubyGems version 1.3.6 Rack version 1.3 -Rails version 4.0.0.beta +Rails version 4.0.0 JavaScript Runtime Node.js (V8) -Active Record version 4.0.0.beta -Action Pack version 4.0.0.beta -Action Mailer version 4.0.0.beta -Active Support version 4.0.0.beta +Active Record version 4.0.0 +Action Pack version 4.0.0 +Action Mailer version 4.0.0 +Active Support version 4.0.0 Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag Application root /home/foobar/commandsapp Environment development @@ -468,12 +474,13 @@ Rails comes with a test suite called `Test::Unit`. Rails owes its stability to t The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. -The `tmp:` namespaced tasks will help you clear the `Rails.root/tmp` directory: +The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory: * `rake tmp:cache:clear` clears `tmp/cache`. * `rake tmp:sessions:clear` clears `tmp/sessions`. * `rake tmp:sockets:clear` clears `tmp/sockets`. * `rake tmp:clear` clears all the three: cache, sessions and sockets. +* `rake tmp:create` creates tmp directories for sessions, cache, sockets, and pids. ### Miscellaneous diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index 0bfa646b81..24e16ecd40 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -184,7 +184,9 @@ Ruby on Rails has two main sets of documentation: the guides help you in learnin You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see [Translating Rails Guides](https://wiki.github.com/rails/docrails/translating-rails-guides). -If you're confident about your changes, you can push them directly yourself via [docrails](https://github.com/rails/docrails). Docrails is a branch with an **open commit policy** and public write access. Commits to docrails are still reviewed, but this happens after they are pushed. Docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. +You can either ask for commit bit if you'd like to contribute to [Docrails](http://github.com/rails/docrails) regularly (Please contact anyone from [the core team](http://rubyonrails.org/core)), or else open a pull request to [Rails](http://github.com/rails/rails) itself. + +Docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. If you are unsure of the documentation changes, you can create an issue in the [Rails](https://github.com/rails/rails/issues) issues tracker on GitHub. @@ -232,8 +234,8 @@ workflow with the [rails-dev-box](https://github.com/rails/rails-dev-box). As a compromise, test what your code obviously affects, and if the change is not in railties run the whole test suite of the affected component. If all is -green that's enough to propose your contribution. We have [Travis CI](https -://travis-ci.org/) as a safety net for catching unexpected breakages +green that's enough to propose your contribution. We have [Travis CI](https://travis-ci.org/rails/rails) +as a safety net for catching unexpected breakages elsewhere. TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted. diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 70055c1d7d..98f91c1ac6 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -248,7 +248,7 @@ Make sure you have started your web server with the option `--debugger`: ```bash $ rails server --debugger => Booting WEBrick -=> Rails 3.2.13 application starting on http://0.0.0.0:3000 +=> Rails 4.0.0 application starting on http://0.0.0.0:3000 => Debugger enabled ... ``` @@ -504,7 +504,7 @@ TIP: You can use the debugger while using `rails console`. Just remember to `req ``` $ rails console -Loading development environment (Rails 3.2.13) +Loading development environment (Rails 4.0.0) >> require "debugger" => [] >> author = Author.first @@ -648,7 +648,7 @@ In this section, you will learn how to find and fix such leaks by using tool suc [Valgrind](http://valgrind.org/) is a Linux-only application for detecting C-based memory leaks and race conditions. -There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls `malloc()` but is doesn't properly call `free()`, this memory won't be available until the app terminates. +There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, if a C extension in the interpreter calls `malloc()` but doesn't properly call `free()`, this memory won't be available until the app terminates. For further information on how to install Valgrind and use with Ruby, refer to [Valgrind and Ruby](http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/) by Evan Weaver. @@ -661,6 +661,8 @@ There are some Rails plugins to help you to find errors and debug your applicati * [Query Trace](https://github.com/ntalbott/query_trace/tree/master) Adds query origin tracing to your logs. * [Query Reviewer](https://github.com/nesquena/query_reviewer) This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed. * [Exception Notifier](https://github.com/smartinez87/exception_notification/tree/master) Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. +* [Better Errors](https://github.com/charliesome/better_errors) Replaces the standard Rails error page with a new one containing more contextual information, like source code and variable inspection. +* [RailsPanel](https://github.com/dejan/rails_panel) Chrome extension for Rails development that will end your tailing of development.log. Have all information about your Rails app requests in the browser - in the Developer Tools panel. Provides insight to db/rendering/total times, parameter list, rendered views and more. References ---------- diff --git a/guides/source/engines.md b/guides/source/engines.md index bc66ed256e..d714f84731 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -346,7 +346,7 @@ Next, the partial that this line will render needs to exist. Create a new direct <h3>New comment</h3> <%= form_for [@post, @post.comments.build] do |f| %> <p> - <%= f.label :text %><br /> + <%= f.label :text %><br> <%= f.text_area :text %> </p> <%= f.submit %> @@ -515,7 +515,7 @@ First, the `author_name` text field needs to be added to the `app/views/blorgh/p ```html+erb <div class="field"> - <%= f.label :author_name %><br /> + <%= f.label :author_name %><br> <%= f.text_field :author_name %> </div> ``` diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md index b409534cb0..11e8db9e88 100644 --- a/guides/source/form_helpers.md +++ b/guides/source/form_helpers.md @@ -553,7 +553,7 @@ outputs (with actual option values omitted for brevity) which results in a `params` hash like ```ruby -{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}} +{'person' => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}} ``` When this is passed to `Person.new` (or `update`), Active Record spots that these parameters should all be used to construct the `birth_date` attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as `Date.civil`. @@ -881,19 +881,19 @@ end ```ruby { - :person => { - :name => 'John Doe', - :addresses_attributes => { - '0' => { - :kind => 'Home', - :street => '221b Baker Street', - }, - '1' => { - :kind => 'Office', - :street => '31 Spooner Street' - } - } + 'person' => { + 'name' => 'John Doe', + 'addresses_attributes' => { + '0' => { + 'kind' => 'Home', + 'street' => '221b Baker Street' + }, + '1' => { + 'kind' => 'Office', + 'street' => '31 Spooner Street' + } } + } } ``` @@ -973,4 +973,4 @@ As a convenience you can instead pass the symbol `:all_blank` which will create ### Adding Fields on the Fly -Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new child' button. Rails does not provide any builtin support for this. When generating new sets of fields you must ensure the the key of the associated array is unique - the current javascript date (milliseconds after the epoch) is a common choice. +Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new child' button. Rails does not provide any builtin support for this. When generating new sets of fields you must ensure the key of the associated array is unique - the current javascript date (milliseconds after the epoch) is a common choice. diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 0d44f0e776..9b2fa315a1 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -138,7 +138,7 @@ application. Most of the work in this tutorial will happen in the `app/` folder, |config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html)| |config.ru|Rack configuration for Rack based servers used to start the application.| |db/|Contains your current database schema, as well as the database migrations.| -|Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) | +|Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) | |lib/|Extended modules for your application.| |log/|Application log files.| |public/|The only folder seen to the world as-is. Contains the static files and compiled assets.| @@ -230,16 +230,16 @@ Blog::Application.routes.draw do # first created -> highest priority. # ... # You can have the root of your site routed with "root" - # root to: "welcome#index" + # root "welcome#index" ``` -This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with `root :to` and uncomment it. It should look something like the following: +This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with `root` and uncomment it. It should look something like the following: ```ruby -root to: "welcome#index" +root "welcome#index" ``` -The `root to: "welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to <http://localhost:3000/welcome/index> to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`). +The `root "welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to <http://localhost:3000/welcome/index> to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`). If you navigate to <http://localhost:3000> in your browser, you'll see the `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, indicating that this new route is indeed going to `WelcomeController`'s `index` action and is rendering the view correctly. @@ -252,23 +252,26 @@ Now that you've seen how to create a controller, an action and a view, let's cre In the Blog application, you will now create a new _resource_. A resource is the term used for a collection of similar objects, such as posts, people or animals. You can create, read, update and destroy items for a resource and these operations are referred to as _CRUD_ operations. -Rails provides a `resources` method which can be used to declare a -standard REST resource. Here's how `config/routes.rb` will look like. +Rails provides a `resources` method which can be used to declare a standard REST resource. +Here's what `config/routes.rb` should look like after the _post resource_ is declared. ```ruby Blog::Application.routes.draw do resources :posts - root to: "welcome#index" + root "welcome#index" end ``` -If you run `rake routes`, you'll see that all the routes for the -standard RESTful actions. +If you run `rake routes`, you'll see that it has defined routes for all the +standard RESTful actions. The meaning of the prefix column (and other columns) +will be seen later, but for now notice that Rails has inferred the +singular form `post` and makes meaningful use of the distinction. ```bash $ rake routes + Prefix Verb URI Pattern Controller#Action posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#new @@ -394,9 +397,27 @@ Edit the `form_for` line inside `app/views/posts/new.html.erb` to look like this <%= form_for :post, url: posts_path do |f| %> ``` -In this example, the `posts_path` helper is passed to the `:url` option. What Rails will do with this is that it will point the form to the `create` action of the current controller, the `PostsController`, and will send a `POST` request to that route. - -By using the `post` method rather than the `get` method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web. +In this example, the `posts_path` helper is passed to the `:url` option. +To see what Rails will do with this, we look back at the output of +`rake routes`: +```bash +$ rake routes + Prefix Verb URI Pattern Controller#Action + posts GET /posts(.:format) posts#index + POST /posts(.:format) posts#create + new_post GET /posts/new(.:format) posts#new +edit_post GET /posts/:id/edit(.:format) posts#edit + post GET /posts/:id(.:format) posts#show + PATCH /posts/:id(.:format) posts#update + PUT /posts/:id(.:format) posts#update + DELETE /posts/:id(.:format) posts#destroy + root / welcome#index +``` +The `posts_path` helper tells Rails to point the form +to the URI Pattern associated with the `posts` prefix; and +the form will (by default) send a `POST` request +to that route. This is associated with the +`create` action of the current controller, the `PostsController`. With the form and its associated route defined, you will be able to fill in the form and then click the submit button to begin the process of creating a new post, so go ahead and do that. When you submit the form, you should see a familiar error: @@ -531,27 +552,19 @@ and change the `create` action to look like this: ```ruby def create - @post = Post.new(post_params) + @post = Post.new(params[:post]) @post.save redirect_to @post end - -private - def post_params - params.require(:post).permit(:title, :text) - end ``` Here's what's going on: every Rails model can be initialized with its respective attributes, which are automatically mapped to the respective -database columns. In the first line we do just that (remember that -`post_params` contains the attributes we're interested in). Then, -`@post.save` is responsible for saving the model in the database. -Finally, we redirect the user to the `show` action, -which we'll define later. - -TIP: Note that `def post_params` is private. This new approach prevents an attacker from setting the model's attributes by manipulating the hash passed to the model. For more information, refer to [this blog post about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). +database columns. In the first line we do just that +(remember that `params[:post]` contains the attributes we're interested in). +Then, `@post.save` is responsible for saving the model in the database. +Finally, we redirect the user to the `show` action, which we'll define later. TIP: As we'll see later, `@post.save` returns a boolean indicating whether the model was saved or not. @@ -612,11 +625,16 @@ we want to accept in our controllers. In this case, we want to allow the look like this: ``` - def create - @post = Post.new(params[:post].permit(:title, :text)) +def create + @post = Post.new(post_params) - @post.save - redirect_to @post + @post.save + redirect_to @post +end + +private + def post_params + params.require(:post).permit(:title, :text) end ``` @@ -626,6 +644,11 @@ Visit <http://localhost:3000/posts/new> and give it a try! ![Show action for posts](images/getting_started/show_action_for_posts.png) +TIP: Note that `def post_params` is private. This new approach prevents an attacker from +setting the model's attributes by manipulating the hash passed to the model. +For more information, refer to +[this blog post about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). + ### Listing all posts We still need a way to list all our posts, so let's do that. @@ -721,7 +744,7 @@ TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server when a change is made. -### Allowing the update of fields +### Adding Some Validation The model file, `app/models/post.rb` is about as simple as it can get: @@ -736,8 +759,6 @@ your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another. -### Adding Some Validation - Rails includes methods to help you validate the data that you send to models. Open the `app/models/post.rb` file and edit it: @@ -767,7 +788,7 @@ def new end def create - @post = Post.new(params[:post].permit(:title, :text)) + @post = Post.new(post_params) if @post.save redirect_to @post @@ -775,6 +796,11 @@ def create render 'new' end end + +private + def post_params + params.require(:post).permit(:title, :text) + end ``` The `new` action is now creating a new instance variable called `@post`, and @@ -793,7 +819,7 @@ something went wrong. To do that, you'll modify ```html+erb <%= form_for :post, url: posts_path do |f| %> <% if @post.errors.any? %> - <div id="errorExplanation"> + <div id="error_explanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> @@ -862,7 +888,7 @@ it look as follows: <%= form_for :post, url: post_path(@post.id), method: :patch do |f| %> <% if @post.errors.any? %> - <div id="errorExplanation"> + <div id="error_explanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> @@ -905,12 +931,17 @@ Next we need to create the `update` action in `app/controllers/posts_controller. def update @post = Post.find(params[:id]) - if @post.update(params[:post].permit(:title, :text)) + if @post.update(post_params) redirect_to @post else render 'edit' end end + +private + def post_params + params.require(:post).permit(:title, :text) + end ``` The new method, `update`, is used when you want to update a record @@ -918,6 +949,8 @@ that already exists, and it accepts a hash containing the attributes that you want to update. As before, if there was an error updating the post we want to show the form back to the user. +We reuse the `post_params` method that we defined earlier for the create action. + TIP: You don't need to pass all attributes to `update`. For example, if you'd call `@post.update(title: 'A new title')` Rails would only update the `title` attribute, leaving all other @@ -977,7 +1010,7 @@ content: ```html+erb <%= form_for @post do |f| %> <% if @post.errors.any? %> - <div id="errorExplanation"> + <div id="error_explanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> @@ -1004,9 +1037,14 @@ content: ``` Everything except for the `form_for` declaration remained the same. -How `form_for` can figure out the right `action` and `method` attributes -when building the form will be explained in just a moment. For now, let's update the -`app/views/posts/new.html.erb` view to use this new partial, rewriting it +The reason we can use this shorter, simpler `form_for` declaration +to stand in for either of the other forms is that `@post` is a *resource* +corresponding to a full set of RESTful routes, and Rails is able to infer +which URI and method to use. +For more information about this use of `form_for`, see +[Resource-oriented style](//api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for-label-Resource-oriented+style). + +Now, let's update the `app/views/posts/new.html.erb` view to use this new partial, rewriting it completely: ```html+erb @@ -1062,7 +1100,7 @@ You can call `destroy` on Active Record objects when you want to delete them from the database. Note that we don't need to add a view for this action since we're redirecting to the `index` action. -Finally, add a 'destroy' link to your `index` action template +Finally, add a 'Destroy' link to your `index` action template (`app/views/posts/index.html.erb`) to wrap everything together. @@ -1088,8 +1126,8 @@ together. </table> ``` -Here we're using `link_to` in a different way. We pass the named route as the first argument, -and then the final two keys as another argument. The `:method` and `:'data-confirm'` +Here we're using `link_to` in a different way. We pass the named route as the second argument, +and then the options as another argument. The `:method` and `:'data-confirm'` options are used as HTML5 attributes so that when the link is clicked, Rails will first show a confirm dialog to the user, and then submit the link with method `delete`. This is done via the JavaScript file `jquery_ujs` which is automatically included @@ -1277,11 +1315,11 @@ So first, we'll wire up the Post show template <h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> <p> - <%= f.label :commenter %><br /> + <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> - <%= f.label :body %><br /> + <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> @@ -1303,9 +1341,14 @@ Let's wire up the `create` in `app/controllers/comments_controller.rb`: class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) - @comment = @post.comments.create(params[:comment].permit(:commenter, :body)) + @comment = @post.comments.create(comment_params) redirect_to post_path(@post) end + + private + def comment_params + params.require(:comment).permit(:commenter, :body) + end end ``` @@ -1352,11 +1395,11 @@ template. This is where we want the comment to show, so let's add that to the <h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> <p> - <%= f.label :commenter %><br /> + <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> - <%= f.label :body %><br /> + <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> @@ -1418,11 +1461,11 @@ following: <h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> <p> - <%= f.label :commenter %><br /> + <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> - <%= f.label :body %><br /> + <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> @@ -1448,11 +1491,11 @@ create a file `app/views/comments/_form.html.erb` containing: ```html+erb <%= form_for([@post, @post.comments.build]) do |f| %> <p> - <%= f.label :commenter %><br /> + <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> - <%= f.label :body %><br /> + <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> @@ -1527,10 +1570,9 @@ controller (`app/controllers/comments_controller.rb`): ```ruby class CommentsController < ApplicationController - def create @post = Post.find(params[:post_id]) - @comment = @post.comments.create(params[:comment]) + @comment = @post.comments.create(comment_params) redirect_to post_path(@post) end @@ -1541,6 +1583,10 @@ class CommentsController < ApplicationController redirect_to post_path(@post) end + private + def comment_params + params.require(:comment).permit(:commenter, :body) + end end ``` @@ -1659,7 +1705,7 @@ Two very common sources of data that are not UTF-8: in the browser. This also applies to your i18n translation files. Most editors that do not already default to UTF-8 (such as some versions of Dreamweaver) offer a way to change the default to UTF-8. Do so. -* Your database. Rails defaults to converting data from your database into UTF-8 at +* Your database: Rails defaults to converting data from your database into UTF-8 at the boundary. However, if your database is not using UTF-8 internally, it may not be able to store all characters that your users enter. For instance, if your database is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 9e5278c92b..2b116c337a 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -21,6 +21,11 @@ This guide will walk you through the I18n API and contains a tutorial on how to After reading this guide, you will know: +* How I18n works in Ruby on Rails +* How to correctly use I18n into a RESTful application in various ways +* How to use I18n to translate ActiveRecord errors or ActionMailer E-mail subjects +* Some other tools to go further with the translation process of your application + -------------------------------------------------------------------------------- NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails [I18n Wiki](http://rails-i18n.org/wiki) for more information. @@ -253,7 +258,7 @@ You would probably need to map URLs like these: ```ruby # config/routes.rb -match '/:locale' => 'dashboard#index' +get '/:locale' => 'dashboard#index' ``` Do take special care about the **order of your routes**, so this route declaration does not "eat" other ones. (You may want to add it directly before the `root :to` declaration.) @@ -283,7 +288,7 @@ def extract_locale_from_accept_language_header end ``` -Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb). +Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master) or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb). #### Using GeoIP (or Similar) Database diff --git a/guides/source/index.html.erb b/guides/source/index.html.erb index a8e4525c67..57c224c165 100644 --- a/guides/source/index.html.erb +++ b/guides/source/index.html.erb @@ -19,7 +19,7 @@ Ruby on Rails Guides <h3><%= section['name'] %></h3> <dl> <% section['documents'].each do |document| %> - <%= guide(document['name'], document['url'], :work_in_progress => document['work_in_progress']) do %> + <%= guide(document['name'], document['url'], work_in_progress: document['work_in_progress']) do %> <p><%= document['description'] %></p> <% end %> <% end %> diff --git a/guides/source/initialization.md b/guides/source/initialization.md index 738591659d..11c736585f 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -7,14 +7,17 @@ as of Rails 4. It is an extremely in-depth guide and recommended for advanced Ra After reading this guide, you will know: * How to use `rails server`. +* The timeline of Rails' initialization sequence. +* Where different files are required by the boot sequence. +* How the Rails::Server interface is defined and used. -------------------------------------------------------------------------------- This guide goes through every method call that is required to boot up the Ruby on Rails stack for a default Rails 4 application, explaining each part in detail along the way. For this -guide, we will be focusing on what happens when you execute +rails -server+ to boot your app. +guide, we will be focusing on what happens when you execute `rails server` +to boot your app. NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified. @@ -26,7 +29,7 @@ quickly. Launch! ------- -Now we finally boot and initialize the app. It all starts with your app's +Let's start to boot and initialize the app. It all begins with your app's `bin/rails` executable. A Rails application is usually started by running `rails console` or `rails server`. @@ -57,7 +60,8 @@ require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) In a standard Rails application, there's a `Gemfile` which declares all dependencies of the application. `config/boot.rb` sets `ENV['BUNDLE_GEMFILE']` to the location of this file. If the Gemfile -exists, `bundler/setup` is then required. +exists, then `bundler/setup` is required. The require is used by Bundler to +configure the load path for your Gemfile's dependencies. A standard Rails application depends on several gems, specifically: @@ -251,9 +255,9 @@ set earlier) is required. ### `config/application` -When `require APP_PATH` is executed, `config/application.rb` is loaded. -This file exists in your app and it's free for you to change based -on your needs. +When `require APP_PATH` is executed, `config/application.rb` is loaded (recall +that `APP_PATH` is defined in `bin/rails`). This file exists in your application +and it's free for you to change based on your needs. ### `Rails::Server#start` @@ -443,7 +447,9 @@ I18n and Rails configuration are all being defined here. ### Back to `config/environment.rb` -When `config/application.rb` has finished loading Rails, and defined +The rest of `config/application.rb` defines the configuration for the +`Rails::Application` which will be used once the application is fully +initialized. When `config/application.rb` has finished loading Rails and defined the application namespace, we go back to `config/environment.rb`, where the application is initialized. For example, if the application was called `Blog`, here we would find `Blog::Application.initialize!`, which is @@ -471,6 +477,13 @@ traverses all the class ancestors looking for an `initializers` method, sorting them and running them. For example, the `Engine` class will make all the engines available by providing the `initializers` method. +The `Rails::Application` class, as defined in `railties/lib/rails/application.rb` +defines `bootstrap`, `railtie`, and `finisher` initializers. The `bootstrap` initializers +prepare the application (like initializing the logger) while the `finisher` +initializers (like building the middleware stack) are run last. The `railtie` +initializers are the initializers which have been defined on the `Rails::Application` +itself and are run between the `bootstrap` and `finishers`. + After this is done we go back to `Rack::Server` ### Rack: lib/rack/server.rb diff --git a/guides/source/kindle/toc.html.erb b/guides/source/kindle/toc.html.erb index e013797dee..f310edd3a1 100644 --- a/guides/source/kindle/toc.html.erb +++ b/guides/source/kindle/toc.html.erb @@ -20,5 +20,5 @@ Ruby on Rails Guides <ul> <li><a href="credits.html">Credits</a></li> <li><a href="copyright.html">Copyright & License</a></li> -<ul> +</ul> </div> diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index 379deb6094..71d3c5638b 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -101,12 +101,14 @@ You're encouraged to help improve the quality of this guide. </p> <p> - If you see any typos or factual errors you are confident to - patch, please clone the <%= link_to 'rails', 'https://github.com/rails/rails' %> - repository and open a new pull request. You can also ask for commit rights on - <%= link_to 'docrails', 'https://github.com/rails/docrails' %> if you plan to submit - several patches. Commits are reviewed, but that happens after you've submitted your - contribution. This repository is cross-merged with master periodically. + If you see any typos or factual errors that you are confident to fix, + you can push the fix to <%= link_to 'docrails', 'https://github.com/rails/docrails' %> (Ask + the <%= link_to 'Rails core team', 'http://rubyonrails.org/core' %> for push access). + If you choose to open a pull request, please do it in <%= link_to 'Rails', 'https://github.com/rails/rails' %> + and not in the <%= link_to 'docrails', 'https://github.com/rails/docrails' %> repository. + Commits made to docrails are still reviewed, but that happens after you've submitted your + contribution. <%= link_to 'docrails', 'https://github.com/rails/docrails' %> is + cross-merged with master periodically. </p> <p> You may also find incomplete content, or stuff that is not up to date. diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index 1ab841b137..5b6e5387ff 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -88,7 +88,7 @@ If we want to display the properties of all the books in our view, we can do so <% end %> </table> -<br /> +<br> <%= link_to "New book", new_book_path %> ``` @@ -592,7 +592,7 @@ def index end def show - @book = Book.find_by_id(params[:id]) + @book = Book.find_by(id: params[:id]) if @book.nil? render action: "index" end @@ -607,7 +607,7 @@ def index end def show - @book = Book.find_by_id(params[:id]) + @book = Book.find_by(id: params[:id]) if @book.nil? redirect_to action: :index end @@ -626,10 +626,10 @@ def index end def show - @book = Book.find_by_id(params[:id]) + @book = Book.find_by(id: params[:id]) if @book.nil? @books = Book.all - flash[:alert] = "Your book was not found" + flash.now[:alert] = "Your book was not found" render "index" end end @@ -1026,7 +1026,7 @@ You can also pass local variables into partials, making them even more powerful ```html+erb <%= form_for(zone) do |f| %> <p> - <b>Zone name</b><br /> + <b>Zone name</b><br> <%= f.text_field :name %> </p> <p> diff --git a/guides/source/migrations.md b/guides/source/migrations.md index 508e52a77c..e6d1e71f5e 100644 --- a/guides/source/migrations.md +++ b/guides/source/migrations.md @@ -314,7 +314,7 @@ will produce a migration that looks like this class AddDetailsToProducts < ActiveRecord::Migration def change add_column :products, :price, precision: 5, scale: 2 - add_reference :products, :user, polymorphic: true, index: true + add_reference :products, :supplier, polymorphic: true, index: true end end ``` @@ -376,7 +376,7 @@ create_join_table :products, :categories, column_options: {null: true} will create the `product_id` and `category_id` with the `:null` option as `true`. -You can pass the option `:table_name` with you want to customize the table +You can pass the option `:table_name` when you want to customize the table name. For example, ```ruby @@ -841,7 +841,6 @@ class AddFlagToProduct < ActiveRecord::Migration reversible do |dir| dir.up { Product.update_all flag: false } end - Product.update_all flag: false end end ``` diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md index f8062a1f7c..0c70f379be 100644 --- a/guides/source/rails_application_templates.md +++ b/guides/source/rails_application_templates.md @@ -227,3 +227,22 @@ git :init git add: "." git commit: "-a -m 'Initial commit'" ``` + +Advanced Usage +-------------- + +The application template is evaluated in the context of a +`Rails::Generators::AppGenerator` instance. It uses the `apply` action +provided by +[Thor](https://github.com/erikhuda/thor/blob/master/lib/thor/actions.rb#L207). +This means you can extend and change the instance to match your needs. + +For example by overwriting the `source_paths` method to contain the +location of your template. Now methods like `copy_file` will accept +relative paths to your template's location. + +```ruby +def source_paths + [File.expand_path(File.dirname(__FILE__))] +end +``` diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index d144fba762..b1a7865d10 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -326,7 +326,7 @@ The following shows how to replace use `Rack::Builder` instead of the Rails supp config.middleware.clear ``` -<br /> +<br> <strong>Add a `config.ru` file to `Rails.root`</strong> ```ruby diff --git a/guides/source/routing.md b/guides/source/routing.md index 076b9dd176..76c4c25108 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -171,6 +171,12 @@ A singular resourceful route generates these helpers: As with plural resources, the same helpers ending in `_url` will also include the host, port and path prefix. +WARNING: A [long-standing bug](https://github.com/rails/rails/issues/1769) prevents `form_for` from working automatically with singular resources. As a workaround, specify the URL for the form directly, like so: + +```ruby +form_for @geocoder, url: geocoder_path do |f| +``` + ### Controller Namespaces and Routing You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an `Admin::` namespace. You would place these controllers under the `app/controllers/admin` directory, and you can group them together in your router: @@ -767,11 +773,11 @@ You can also reuse dynamic segments from the match in the path to redirect to: get '/stories/:name', to: redirect('/posts/%{name}') ``` -You can also provide a block to redirect, which receives the params and the request object: +You can also provide a block to redirect, which receives the symbolized path parameters and the request object: ```ruby -get '/stories/:name', to: redirect {|params, req| "/posts/#{params[:name].pluralize}" } -get '/stories', to: redirect {|p, req| "/posts/#{req.subdomain}" } +get '/stories/:name', to: redirect {|path_params, req| "/posts/#{path_params[:name].pluralize}" } +get '/stories', to: redirect {|path_params, req| "/posts/#{req.subdomain}" } ``` Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible. diff --git a/guides/source/testing.md b/guides/source/testing.md index 416a8b592f..62c9835fa4 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -92,7 +92,7 @@ user_<%= n %>: #### Fixtures in Action -Rails by default automatically loads all fixtures from the `test/fixtures` folder for your unit and functional test. Loading involves three steps: +Rails by default automatically loads all fixtures from the `test/fixtures` folder for your models and controllers test. Loading involves three steps: * Remove any existing data from the table corresponding to the fixture * Load the fixture data into the table @@ -116,7 +116,7 @@ email(david.girlfriend.email, david.location_tonight) Unit Testing your Models ------------------------ -In Rails, unit tests are what you write to test your models. +In Rails, models tests are what you write to test your models. For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary. diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 35a9617b80..5992e94cd8 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -61,7 +61,7 @@ end ```ruby class UsersController < ApplicationController def update_name - # Change needed; form_for will try to use a non-existant PATCH route. + # Change needed; form_for will try to use a non-existent PATCH route. end end ``` @@ -131,7 +131,15 @@ The following changes are meant for upgrading your application to Rails 4.0. ### Gemfile -Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that line from your Gemfile when upgrading. +Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that +line from your Gemfile when upgrading. You should also update your application +file (in `config/application.rb`): + +```ruby +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(:default, Rails.env) +``` ### vendor/plugins @@ -149,6 +157,9 @@ Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must rep * Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) to a smoothly upgrade path. +* If you are not using Protected Attributes, you can remove any options related to +this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options. + * Rails 4.0 requires that scopes use a callable object such as a Proc or lambda: ```ruby @@ -194,16 +205,6 @@ If you are relying on the ability for external applications or Javascript to be * Rails 4.0 encrypts the contents of cookie-based sessions if `secret_key_base` has been set. Rails 3.x signed, but did not encrypt, the contents of cookie-based session. Signed cookies are "secure" in that they are verified to have been generated by your app and are tamper-proof. However, the contents can be viewed by end users, and encrypting the contents eliminates this caveat/concern without a significant performance penalty. -As described above, existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing `secret_token` in place and add the new `secret_key_base`. - -```ruby - # config/initializers/secret_token.rb - Myapp::Application.config.secret_token = 'existing secret token' - Myapp::Application.config.secret_key_base = 'new secret key base' -``` - -The same caveats apply here, too. You should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. You should also take care to make sure you are not relying on the ability to decode signed cookies generated by your app in external applications or Javascript before upgrading. - Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for details on the move to encrypted session cookies. * Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature. @@ -218,6 +219,11 @@ Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for d * Rails 4.0 deprecates the `dom_id` and `dom_class` methods in controllers (they are fine in views). You will need to include the `ActionView::RecordIdentifier` module in controllers requiring this feature. +* Rails 4.0 deprecates the `:confirm` option for the `link_to` helper. You should +instead rely on a data attribute (e.g. `data: { confirm: 'Are you sure?' }`). +This deprecation also concerns the helpers based on this one (such as `link_to_if` +or `link_to_unless`). + * Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`. * Rails 4.0 raises an `ArgumentError` if clashing named routes are defined. This can be triggered by explicitly defined named routes or by the `resources` method. Here are two examples that clash with routes named `example_path`: @@ -305,6 +311,12 @@ Active Record Observer and Action Controller Sweeper have been extracted to the ### sprockets-rails * `assets:precompile:primary` has been removed. Use `assets:precompile` instead. +* The `config.assets.compress` option should be changed to +`config.assets.js_compressor` like so for instance: + +```ruby +config.assets.js_compressor = :uglifier +``` ### sass-rails diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md index 22a59cdfec..bd0c796673 100644 --- a/guides/source/working_with_javascript_in_rails.md +++ b/guides/source/working_with_javascript_in_rails.md @@ -278,9 +278,7 @@ The index view (`app/views/users/index.html.erb`) contains: <b>Users</b> <ul id="users"> -<% @users.each do |user| %> - <%= render user %> -<% end %> +<%= render @users %> </ul> <br> |