diff options
Diffstat (limited to 'guides')
43 files changed, 855 insertions, 453 deletions
diff --git a/guides/Rakefile b/guides/Rakefile index 7881a3d9b3..d6dd950d01 100644 --- a/guides/Rakefile +++ b/guides/Rakefile @@ -13,6 +13,12 @@ namespace :guides do desc "Generate .mobi file. The kindlegen executable must be in your PATH. You can get it for free from http://www.amazon.com/kindlepublishing" task :kindle do + unless `kindlerb -v 2> /dev/null` =~ /kindlerb 0.1.1/ + abort "Please `gem install kindlerb`" + end + unless `convert` =~ /convert/ + abort "Please install ImageMagick`" + end ENV['KINDLE'] = '1' Rake::Task['guides:generate:html'].invoke end diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb index 3b124ef236..af9c5b8372 100644 --- a/guides/rails_guides/generator.rb +++ b/guides/rails_guides/generator.rb @@ -84,7 +84,7 @@ module RailsGuides @warnings = ENV['WARNINGS'] == '1' @all = ENV['ALL'] == '1' @kindle = ENV['KINDLE'] == '1' - @version = ENV['RAILS_VERSION'] || `git rev-parse --short HEAD`.chomp + @version = ENV['RAILS_VERSION'] || 'local' @lang = ENV['GUIDES_LANGUAGE'] end @@ -112,11 +112,9 @@ module RailsGuides end def generate_mobi - opf = "#{output_dir}/rails_guides.opf" + require 'rails_guides/kindle' out = "#{output_dir}/kindlegen.out" - - system "kindlegen #{opf} -o #{mobi} > #{out} 2>&1" - puts "Guides compiled as Kindle book to #{mobi}" + Kindle.generate(output_dir, mobi, out) puts "(kindlegen log at #{out})." end diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb new file mode 100644 index 0000000000..09eecd5634 --- /dev/null +++ b/guides/rails_guides/kindle.rb @@ -0,0 +1,119 @@ +#!/usr/bin/env ruby + +unless `which kindlerb` + abort "Please gem install kindlerb" +end + +require 'nokogiri' +require 'fileutils' +require 'yaml' +require 'date' + +module Kindle + extend self + + def generate(output_dir, mobi_outfile, logfile) + output_dir = File.absolute_path(output_dir) + Dir.chdir output_dir do + puts "=> Using output dir: #{output_dir}" + puts "=> Arranging html pages in document order" + toc = File.read("toc.ncx") + doc = Nokogiri::XML(toc).xpath("//ncx:content", 'ncx' => "http://www.daisy.org/z3986/2005/ncx/") + html_pages = doc.select {|c| c[:src]}.map {|c| c[:src]}.uniq + + generate_front_matter(html_pages) + + generate_sections(html_pages) + + generate_document_metadata(mobi_outfile) + + puts "Creating MOBI document with kindlegen. This make take a while." + cmd = "kindlerb . > #{File.absolute_path logfile} 2>&1" + puts cmd + system(cmd) + puts "MOBI document generated at #{File.expand_path(mobi_outfile, output_dir)}" + end + end + + def generate_front_matter(html_pages) + frontmatter = [] + html_pages.delete_if {|x| + if x =~ /(toc|welcome|credits|copyright).html/ + frontmatter << x unless x =~ /toc/ + true + end + } + html = frontmatter.map {|x| + Nokogiri::HTML(File.open(x)).at("body").inner_html + }.join("\n") + + fdoc = Nokogiri::HTML(html) + fdoc.search("h3").each do |h3| + h3.name = 'h4' + end + fdoc.search("h2").each do |h2| + h2.name = 'h3' + h2['id'] = h2.inner_text.gsub(/\s/, '-') + end + add_head_section fdoc, "Front Matter" + File.open("frontmatter.html",'w') {|f| f.puts fdoc.to_html} + html_pages.unshift "frontmatter.html" + end + + def generate_sections(html_pages) + FileUtils::rm_rf("sections/") + html_pages.each_with_index do |page, section_idx| + FileUtils::mkdir_p("sections/%03d" % section_idx) + doc = Nokogiri::HTML(File.open(page)) + title = doc.at("title").inner_text.gsub("Ruby on Rails Guides: ", '') + title = page.capitalize.gsub('.html', '') if title.strip == '' + File.open("sections/%03d/_section.txt" % section_idx, 'w') {|f| f.puts title} + doc.xpath("//h3[@id]").each_with_index do |h3,item_idx| + subsection = h3.inner_text + content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map {|x| x.to_html} + item = Nokogiri::HTML(h3.to_html + content.join("\n")) + item_path = "sections/%03d/%03d.html" % [section_idx, item_idx] + add_head_section(item, subsection) + item.search("img").each do |img| + img['src'] = "#{Dir.pwd}/#{img['src']}" + end + item.xpath("//li/p").each {|p| p.swap(p.children); p.remove} + File.open(item_path, 'w') {|f| f.puts item.to_html} + end + end + end + + def generate_document_metadata(mobi_outfile) + puts "=> Generating _document.yml" + x = Nokogiri::XML(File.open("rails_guides.opf")).remove_namespaces! + cover_jpg = "#{Dir.pwd}/images/rails_guides_kindle_cover.jpg" + cover_gif = cover_jpg.sub(/jpg$/, 'gif') + puts `convert #{cover_jpg} #{cover_gif}` + document = { + 'doc_uuid' => x.at("package")['unique-identifier'], + 'title' => x.at("title").inner_text.gsub(/\(.*$/, " v2"), + 'publisher' => x.at("publisher").inner_text, + 'author' => x.at("creator").inner_text, + 'subject' => x.at("subject").inner_text, + 'date' => x.at("date").inner_text, + 'cover' => cover_gif, + 'masthead' => nil, + 'mobi_outfile' => mobi_outfile + } + puts document.to_yaml + File.open("_document.yml", 'w'){|f| f.puts document.to_yaml} + end + + def add_head_section(doc, title) + head = Nokogiri::XML::Node.new "head", doc + title_node = Nokogiri::XML::Node.new "title", doc + title_node.content = title + title_node.parent = head + css = Nokogiri::XML::Node.new "link", doc + css['rel'] = 'stylesheet' + css['type'] = 'text/css' + css['href'] = "#{Dir.pwd}/stylesheets/kindle.css" + css.parent = head + doc.at("body").before head + end +end diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 42794b180e..dd57787111 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -143,7 +143,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ * `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals. -* Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols). +* Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols). * BufferedLogger is deprecated. Use ActiveSupport::Logger, or the logger from Ruby stdlib. @@ -165,8 +165,48 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railt ### Notable changes +* Adds some metadata columns to `schema_migrations` table. + + * `migrated_at` + * `fingerprint` - an md5 hash of the migration. + * `name` - the filename minus version and extension. + +* Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support. + +* Add `Relation#load` to explicitly load the record and return `self`. + +* `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 custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this: + + store :settings, accessors: [ :color, :homepage ], coder: JSON + +* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`. + +* Remove IdentityMap. + +* 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. + +* Allows PostgreSQL hstore records to be created. + ### Deprecations +* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do. + +* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's + how you can rewrite the code: + + * `find_all_by_...` can be rewritten using `where(...)`. + * `find_last_by_...` can be rewritten using `where(...).last`. + * `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 8bd28d5246..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 @@ -828,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 @@ -849,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 @@ -857,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..6bb3439e5e 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 @@ -516,7 +516,6 @@ The following configuration options are best made in one of the environment file |`perform_deliveries`|Determines whether deliveries are actually carried out when the `deliver` method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.| |`deliveries`|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.| |`default_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to`, etc.).| -|`async`|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to `Rails.queue` for processing.| ### Example Action Mailer Configuration diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md index c931b30bd3..4cdac43a7e 100644 --- a/guides/source/action_view_overview.md +++ b/guides/source/action_view_overview.md @@ -1263,8 +1263,6 @@ 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 %> <label for="file">File to Upload</label> <%= file_field_tag "file" %> @@ -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_record_basics.md b/guides/source/active_record_basics.md index 68c6416e89..883c2dda4a 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -5,9 +5,11 @@ This guide is an introduction to Active Record. After reading this guide, you will know: -* What Object Relational Mapping and Active Record are and how they are used in Rails. +* What Object Relational Mapping and Active Record are and how they are used in + Rails. * How Active Record fits into the Model-View-Controller paradigm. -* How to use Active Record models to manipulate data stored in a relational database. +* How to use Active Record models to manipulate data stored in a relational + database. * Active Record schema naming conventions. * The concepts of database migrations, validations and callbacks. @@ -16,19 +18,34 @@ After reading this guide, you will know: What is Active Record? ---------------------- -Active Record is the M in [MVC](getting_started.html#the-mvc-architecture) - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system. +Active Record is the M in [MVC](getting_started.html#the-mvc-architecture) - the +model - which is the layer of the system responsible for representing business +data and logic. Active Record facilitates the creation and use of business +objects whose data requires persistent storage to a database. It is an +implementation of the Active Record pattern which itself is a description of an +Object Relational Mapping system. ### The Active Record Pattern -Active Record was described by Martin Fowler in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database. +Active Record was described by Martin Fowler in his book _Patterns of Enterprise +Application Architecture_. In Active Record, objects carry both persistent data +and behavior which operates on that data. Active Record takes the opinion that +ensuring data access logic is part of the object will educate users of that +object on how to write to and read from the database. ### Object Relational Mapping -Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code. +Object-Relational Mapping, commonly referred to as its abbreviation ORM, is +a technique that connects the rich objects of an application to tables in +a relational database management system. Using ORM, the properties and +relationships of the objects in an application can be easily stored and +retrieved from a database without writing SQL statements directly and with less +overall database access code. ### Active Record as an ORM Framework -Active Record gives us several mechanisms, the most important being the ability to: +Active Record gives us several mechanisms, the most important being the ability +to: * Represent models and their data * Represent associations between these models @@ -39,14 +56,30 @@ Active Record gives us several mechanisms, the most important being the ability Convention over Configuration in Active Record ---------------------------------------------- -When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating Active Record models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can't follow the conventions for any reason. +When writing applications using other programming languages or frameworks, it +may be necessary to write a lot of configuration code. This is particularly true +for ORM frameworks in general. However, if you follow the conventions adopted by +Rails, you'll need to write very little configuration (in some case no +configuration at all) when creating Active Record models. The idea is that if +you configure your applications in the very same way most of the times then this +should be the default way. In this cases, explicit configuration would be needed +only in those cases where you can't follow the conventions for any reason. ### Naming Conventions -By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class `Book`, you should have a database table called **books**. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples: +By default, Active Record uses some naming conventions to find out how the +mapping between models and database tables should be created. Rails will +pluralize your class names to find the respective database table. So, for +a class `Book`, you should have a database table called **books**. The Rails +pluralization mechanisms are very powerful, being capable to pluralize (and +singularize) both regular and irregular words. When using class names composed +of two or more words, the model class name should follow the Ruby conventions, +using the CamelCase form, while the table name must contain the words separated +by underscores. Examples: * Database Table - Plural with underscores separating words (e.g., `book_clubs`) -* Model Class - Singular with the first letter of each word capitalized (e.g., `BookClub`) +* Model Class - Singular with the first letter of each word capitalized (e.g., +`BookClub`) | Model / Class | Table / Schema | | ------------- | -------------- | @@ -59,34 +92,52 @@ By default, Active Record uses some naming conventions to find out how the mappi ### Schema Conventions -Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. - -* **Foreign keys** - These fields should be named following the pattern `singularized_table_name_id` (e.g., `item_id`, `order_id`). These are the fields that Active Record will look for when you create associations between your models. -* **Primary keys** - By default, Active Record will use an integer column named `id` as the table's primary key. When using [Rails 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 to Active Record instances: - -* `created_at` - Automatically gets set to the current date and time when the record is first created. -* `created_on` - Automatically gets set to the current date when the record is first created. -* `updated_at` - Automatically gets set to the current date and time whenever the record is updated. -* `updated_on` - Automatically gets set to the current date whenever the record is updated. -* `lock_version` - Adds [optimistic locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to a model. -* `type` - Specifies that the model uses [Single Table Inheritance](http://api.rubyonrails.org/classes/ActiveRecord/Base.html) -* `(table_name)_count` - Used to cache the number of belonging objects on associations. For example, a `comments_count` column in a `Post` class that has many instances of `Comment` will cache the number of existent comments for each post. +Active Record uses naming conventions for the columns in database tables, +depending on the purpose of these columns. + +* **Foreign keys** - These fields should be named following the pattern + `singularized_table_name_id` (e.g., `item_id`, `order_id`). These are the + fields that Active Record will look for when you create associations between + your models. +* **Primary keys** - By default, Active Record will use an integer column named + `id` as the table's primary key. When using [Rails + 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 +to Active Record instances: + +* `created_at` - Automatically gets set to the current date and time when the + record is first created. +* `updated_at` - Automatically gets set to the current date and time whenever + the record is updated. +* `lock_version` - Adds [optimistic + locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to + a model. +* `type` - Specifies that the model uses [Single Table + Inheritance](http://api.rubyonrails.org/classes/ActiveRecord/Base.html) +* `(table_name)_count` - Used to cache the number of belonging objects on + associations. For example, a `comments_count` column in a `Post` class that + has many instances of `Comment` will cache the number of existent comments + for each post. NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, `type` is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling. Creating Active Record Models ----------------------------- -It is very easy to create Active Record models. All you have to do is to subclass the `ActiveRecord::Base` class and you're good to go: +It is very easy to create Active Record models. All you have to do is to +subclass the `ActiveRecord::Base` class and you're good to go: ```ruby class Product < ActiveRecord::Base end ``` -This will create a `Product` model, mapped to a `products` table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose that the `products` table was created using an SQL sentence like: +This will create a `Product` model, mapped to a `products` table at the +database. By doing this you'll also have the ability to map the columns of each +row in that table with the attributes of the instances of your model. Suppose +that the `products` table was created using an SQL sentence like: ```sql CREATE TABLE products ( @@ -96,7 +147,8 @@ CREATE TABLE products ( ); ``` -Following the table schema above, you would be able to write code like the following: +Following the table schema above, you would be able to write code like the +following: ```ruby p = Product.new @@ -107,9 +159,12 @@ puts p.name # "Some Book" Overriding the Naming Conventions --------------------------------- -What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions. +What if you need to follow a different naming convention or need to use your +Rails application with a legacy database? No problem, you can easily override +the default conventions. -You can use the `ActiveRecord::Base.table_name=` method to specify the table name that should be used: +You can use the `ActiveRecord::Base.table_name=` method to specify the table +name that should be used: ```ruby class Product < ActiveRecord::Base @@ -117,7 +172,9 @@ class Product < ActiveRecord::Base end ``` -If you do so, you will have to define manually the class name that is hosting the fixtures (class_name.yml) using the `set_fixture_class` method in your test definition: +If you do so, you will have to define manually the class name that is hosting +the fixtures (class_name.yml) using the `set_fixture_class` method in your test +definition: ```ruby class FunnyJoke < ActiveSupport::TestCase @@ -127,7 +184,8 @@ class FunnyJoke < ActiveSupport::TestCase end ``` -It's also possible to override the column that should be used as the table's primary key using the `ActiveRecord::Base.set_primary_key` method: +It's also possible to override the column that should be used as the table's +primary key using the `ActiveRecord::Base.set_primary_key` method: ```ruby class Product < ActiveRecord::Base @@ -138,19 +196,24 @@ end CRUD: Reading and Writing Data ------------------------------ -CRUD is an acronym for the four verbs we use to operate on data: **C**reate, **R**ead, **U**pdate and **D**elete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables. +CRUD is an acronym for the four verbs we use to operate on data: **C**reate, +**R**ead, **U**pdate and **D**elete. Active Record automatically creates methods +to allow an application to read and manipulate data stored within its tables. ### Create -Active Record objects can be created from a hash, a block or have their attributes manually set after creation. The `new` method will return a new object while `create` will return the object and save it to the database. +Active Record objects can be created from a hash, a block or have their +attributes manually set after creation. The `new` method will return a new +object while `create` will return the object and save it to the database. -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: +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") ``` -Using the `new` method, an object can be created without being saved: +Using the `new` method, an object can be instantiated without being saved: ```ruby user = User.new @@ -160,7 +223,8 @@ user.occupation = "Code Artist" 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: +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| @@ -171,7 +235,8 @@ end ### Read -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. +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 @@ -193,11 +258,13 @@ david = User.find_by_name('David') 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. +You can learn more about querying an Active Record model in the [Active Record +Query Interface](active_record_querying.html) guide. ### Update -Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database. +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') @@ -205,9 +272,26 @@ user.name = 'Dave' user.save ``` +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.update_attributes(name: 'Dave') +``` + +This is most useful when updating several attributes at once. If, on the other +hand, you'd like to update several records in bulk, you may find the +`update_all` class method useful: + +```ruby +User.update_all "max_login_attempts = 3, must_change_password = 'true'" +``` + ### Delete -Likewise, once retrieved an Active Record object can be destroyed which removes it from the database. +Likewise, once retrieved an Active Record object can be destroyed which removes +it from the database. ```ruby user = User.find_by_name('David') @@ -217,14 +301,70 @@ user.destroy Validations ----------- -Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the [Active Record Validations and Callbacks guide](active_record_validations_callbacks.html#validations-overview). +Active Record allows you to validate the state of a model before it gets written +into the database. There are several methods that you can use to check your +models and validate that an attribute value is not empty, is unique and not +already in the database, follows a specific format and many more. + +Validation is a very important issue to consider when persisting to database, so +the methods `create`, `save` and `update_attributes` take it into account when +running: they return `false` when validation fails and they didn't actually +perform any operation on database. All of these have a bang counterpart (that +is, `create!`, `save!` and `update_attributes!`), which are stricter in that +they raise the exception `ActiveRecord::RecordInvalid` if validation fails. +A quick example to illustrate: + +```ruby +class User < ActiveRecord::Base + validates_presence_of :name +end + +User.create # => false +User.create! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank +``` + +You can learn more about validations in the [Active Record Validations +guide](active_record_validations.html). Callbacks --------- -Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the [Active Record Validations and Callbacks guide](active_record_validations_callbacks.html#callbacks-overview). +Active Record callbacks allow you to attach code to certain events in the +life-cycle of your models. This enables you to add behavior to your models by +transparently executing code when those events occur, like when you create a new +record, update it, destroy it and so on. You can learn more about callbacks in +the [Active Record Callbacks guide](active_record_callbacks.html). 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. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the [Active Record Migrations guide](migrations.html) +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 +creates a table: + +```ruby +class CreatePublications < ActiveRecord::Migration + def change + create_table :publications do |t| + t.string :title + t.text :description + t.references :publication_type + t.integer :publisher_id + t.string :publisher_type + t.boolean :single_issue + + t.timestamps + end + add_index :publications, :publication_type_id + end +end +``` + +Rails keeps track of which files have been committed to the database and +provides rollback features. To actually create the table, you'd run `rake db:migrate` +and to roll it back, `rake db:rollback`. + +Note that the above code is database-agnostic: it will run in MySQL, postgresql, +Oracle and others. You can learn more about migrations in the [Active Record +Migrations guide](migrations.html) diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index 02c1c46a5a..0a93f61f6d 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. -------------------------------------------------------------------------------- @@ -150,6 +150,7 @@ The following methods trigger callbacks: * `create!` * `decrement!` * `destroy` +* `destroy!` * `destroy_all` * `increment!` * `save` 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 4642ef82f0..822d12aa3a 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. -------------------------------------------------------------------------------- @@ -503,8 +503,8 @@ end ``` If you want to be sure that an association is present, you'll need to test -whether the foreign key used to map the association is present, and not the -associated object itself. +whether the associated object itself is present, and not the foreign key used +to map the association. ```ruby class LineItem < ActiveRecord::Base @@ -513,7 +513,8 @@ class LineItem < ActiveRecord::Base end ``` -You should also be sure to have a proper `:inverse_of` as well: +In order to validate associated records whose presence is required, you must +specify the `:inverse_of` option for the association: ```ruby class Order < ActiveRecord::Base @@ -779,7 +780,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 +797,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 @@ -908,6 +909,146 @@ class Invoice < ActiveRecord::Base end ``` +Working with Validation Errors +------------------------------ + +In addition to the `valid?` and `invalid?` methods covered earlier, Rails provides a number of methods for working with the `errors` collection and inquiring about the validity of objects. + +The following is a list of the most commonly used methods. Please refer to the `ActiveModel::Errors` documentation for a list of all the available methods. + +### `errors` + +Returns an instance of the class `ActiveModel::Errors` containing all errors. Each key is the attribute name and the value is an array of strings with all errors. + +```ruby +class Person < ActiveRecord::Base + validates :name, presence: true, length: { minimum: 3 } +end + +person = Person.new +person.valid? # => false +person.errors + # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]} + +person = Person.new(name: "John Doe") +person.valid? # => true +person.errors # => [] +``` + +### `errors[]` + +`errors[]` is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array. + +```ruby +class Person < ActiveRecord::Base + validates :name, presence: true, length: { minimum: 3 } +end + +person = Person.new(name: "John Doe") +person.valid? # => true +person.errors[:name] # => [] + +person = Person.new(name: "JD") +person.valid? # => false +person.errors[:name] # => ["is too short (minimum is 3 characters)"] + +person = Person.new +person.valid? # => false +person.errors[:name] + # => ["can't be blank", "is too short (minimum is 3 characters)"] +``` + +### `errors.add` + +The `add` method lets you manually add messages that are related to particular attributes. You can use the `errors.full_messages` or `errors.to_a` methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). `add` receives the name of the attribute you want to add the message to, and the message itself. + +```ruby +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add(:name, "cannot contain the characters !@#%*()_-+=") + end +end + +person = Person.create(name: "!@#") + +person.errors[:name] + # => ["cannot contain the characters !@#%*()_-+="] + +person.errors.full_messages + # => ["Name cannot contain the characters !@#%*()_-+="] +``` + +Another way to do this is using `[]=` setter + +```ruby + class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors[:name] = "cannot contain the characters !@#%*()_-+=" + end + end + + person = Person.create(name: "!@#") + + person.errors[:name] + # => ["cannot contain the characters !@#%*()_-+="] + + person.errors.to_a + # => ["Name cannot contain the characters !@#%*()_-+="] +``` + +### `errors[:base]` + +You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can simply add a string to it and it will be used as an error message. + +```ruby +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors[:base] << "This person is invalid because ..." + end +end +``` + +### `errors.clear` + +The `clear` method is used when you intentionally want to clear all the messages in the `errors` collection. Of course, calling `errors.clear` upon an invalid object won't actually make it valid: the `errors` collection will now be empty, but the next time you call `valid?` or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the `errors` collection will be filled again. + +```ruby +class Person < ActiveRecord::Base + validates :name, presence: true, length: { minimum: 3 } +end + +person = Person.new +person.valid? # => false +person.errors[:name] + # => ["can't be blank", "is too short (minimum is 3 characters)"] + +person.errors.clear +person.errors.empty? # => true + +p.save # => false + +p.errors[:name] +# => ["can't be blank", "is too short (minimum is 3 characters)"] +``` + +### `errors.size` + +The `size` method returns the total number of error messages for the object. + +```ruby +class Person < ActiveRecord::Base + validates :name, presence: true, length: { minimum: 3 } +end + +person = Person.new +person.valid? # => false +person.errors.size # => 2 + +person = Person.new(name: "Andrea", email: "andrea@example.com") +person.valid? # => true +person.errors.size # => 0 +``` + Displaying Validation Errors in Views ------------------------------------- diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 775da2a85c..23736020ec 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`: @@ -2675,13 +2678,6 @@ If the receiver responds to `convert_key`, the method is called on each of the a {a: 1}.with_indifferent_access.except("a") # => {} ``` -The method `except` may come in handy for example when you want to protect some parameter that can't be globally protected with `attr_protected`: - -```ruby -params[:account] = params[:account].except(:plan_id) unless admin? -@account.update_attributes(params[:account]) -``` - There's also the bang variant `except!` that removes keys in the very receiver. NOTE: Defined in `active_support/core_ext/hash/except.rb`. @@ -3596,7 +3592,7 @@ Time.zone_default # => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...> # In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST. -t = Time.local_time(2010, 3, 28, 1, 59, 59) +t = Time.local(2010, 3, 28, 1, 59, 59) # => Sun Mar 28 01:59:59 +0100 2010 t.advance(seconds: 1) # => Sun Mar 28 03:00:00 +0200 2010 @@ -3651,26 +3647,6 @@ Time.current Analogously to `DateTime`, the predicates `past?`, and `future?` are relative to `Time.current`. -Use the `local_time` class method to create time objects honoring the user time zone: - -```ruby -Time.zone_default -# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...> -Time.local_time(2010, 8, 15) -# => Sun Aug 15 00:00:00 +0200 2010 -``` - -The `utc_time` class method returns a time in UTC: - -```ruby -Time.zone_default -# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...> -Time.utc_time(2010, 8, 15) -# => Sun Aug 15 00:00:00 UTC 2010 -``` - -Both `local_time` and `utc_time` accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0. - If the time to be constructed lies beyond the range supported by `Time` in the runtime platform, usecs are discarded and a `DateTime` object is returned instead. #### Durations @@ -3689,7 +3665,7 @@ now - 1.week They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform: ```ruby -Time.utc_time(1582, 10, 3) + 5.days +Time.utc(1582, 10, 3) + 5.days # => Mon Oct 18 00:00:00 UTC 1582 ``` 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..743a04ed42 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. @@ -257,7 +272,8 @@ $('#logo').attr src: "<%= asset_path('logo.png') %>" ### Manifest Files and Directives -Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ — instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if `Rails.application.config.assets.compress` is true). By serving one file rather than many, the load time of pages can be greatly reduced because the browser makes fewer requests. +Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ — instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if `Rails.application.config.assets.compress` is true). By serving one file rather than many, the load time of pages can be greatly reduced because the browser makes fewer requests. Compression also reduces the file size enabling the browser to download it faster. + For example, a new Rails application includes a default `app/assets/javascripts/application.js` file which contains the following lines: @@ -270,8 +286,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 +351,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 +476,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 +506,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 +662,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..dd59e2a8df 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. -------------------------------------------------------------------------------- @@ -94,6 +94,25 @@ end NOTE: `belongs_to` associations _must_ use the singular term. If you used the pluralized form in the above example for the `customer` association in the `Order` model, you would be told that there was an "uninitialized constant Order::Customers". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too. +The corresponding migration might look like this: + +```ruby +class CreateOrders < ActiveRecord::Migration + def change + create_table :customers do |t| + t.string :name + t.timestamps + end + + create_table :orders do |t| + t.belongs_to :customer + t.datetime :order_date + t.timestamps + end + end +end +``` + ### The `has_one` Association A `has_one` association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this: @@ -106,6 +125,25 @@ end  +The corresponding migration might look like this: + +```ruby +class CreateSuppliers < ActiveRecord::Migration + def change + create_table :suppliers do |t| + t.string :name + t.timestamps + end + + create_table :accounts do |t| + t.belongs_to :supplier + t.string :account_number + t.timestamps + end + end +end +``` + ### The `has_many` Association A `has_many` association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a `belongs_to` association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this: @@ -120,6 +158,25 @@ NOTE: The name of the other model is pluralized when declaring a `has_many` asso  +The corresponding migration might look like this: + +```ruby +class CreateCustomers < ActiveRecord::Migration + def change + create_table :customers do |t| + t.string :name + t.timestamps + end + + create_table :orders do |t| + t.belongs_to :customer + t.datetime :order_date + t.timestamps + end + end +end +``` + ### The `has_many :through` Association A `has_many :through` association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this: @@ -143,6 +200,31 @@ end  +The corresponding migration might look like this: + +```ruby +class CreateAppointments < ActiveRecord::Migration + def change + create_table :physicians do |t| + t.string :name + t.timestamps + end + + create_table :patients do |t| + t.string :name + t.timestamps + end + + create_table :appointments do |t| + t.belongs_to :physician + t.belongs_to :patient + t.datetime :appointment_date + t.timestamps + end + end +end +``` + The collection of join models can be managed via the API. For example, if you assign ```ruby @@ -199,6 +281,31 @@ end  +The corresponding migration might look like this: + +```ruby +class CreateAccountHistories < ActiveRecord::Migration + def change + create_table :suppliers do |t| + t.string :name + t.timestamps + end + + create_table :accounts do |t| + t.belongs_to :supplier + t.string :account_number + t.timestamps + end + + create_table :account_histories do |t| + t.belongs_to :account + t.integer :credit_rating + t.timestamps + end + end +end +``` + ### The `has_and_belongs_to_many` Association A `has_and_belongs_to_many` association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way: @@ -215,6 +322,29 @@ end  +The corresponding migration might look like this: + +```ruby +class CreateAssembliesAndParts < ActiveRecord::Migration + def change + create_table :assemblies do |t| + t.string :name + t.timestamps + end + + create_table :parts do |t| + t.string :part_number + t.timestamps + end + + create_table :assemblies_parts do |t| + t.belongs_to :assembly + t.belongs_to :part + end + end +end +``` + ### Choosing Between `belongs_to` and `has_one` If you want to set up a one-to-one relationship between two models, you'll need to add `belongs_to` to one, and `has_one` to the other. How do you know which is which? @@ -452,7 +582,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..a8e33a2956 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| @@ -278,6 +276,8 @@ config.middleware.delete ActionDispatch::BestStandardsSupport * `config.active_record.auto_explain_threshold_in_seconds` configures the threshold for automatic EXPLAINs (`nil` disables this feature). Queries exceeding the threshold get their query plan logged. Default is 0.5 in development mode. +* +config.active_record.cache_timestamp_format+ controls the format of the timestamp value in the cache key. Default is +:number+. + The MySQL adapter adds one additional configuration option: * `ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns in a MySQL database to be booleans and is true by default. 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/documents.yaml b/guides/source/documents.yaml index d7c648681d..e779407fab 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -9,6 +9,10 @@ name: Models documents: - + name: Active Record Basics + url: active_record_basics.html + description: This guide will get you started with models, persistence to database and the Active Record pattern and library. + - name: Rails Database Migrations url: migrations.html description: This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner. 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..8ab44ea0bb 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. -------------------------------------------------------------------------------- @@ -458,7 +458,7 @@ As with other helpers, if you were to use the `select` helper on a form builder <%= f.select(:city_id, ...) %> ``` -WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of ` ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) ` when you pass the `params` hash to `Person.new` or `update_attributes`. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of `attr_protected` and `attr_accessible`. For further details on this, see the [Ruby On Rails Security Guide](security.html#mass-assignment). +WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of ` ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) ` when you pass the `params` hash to `Person.new` or `update_attributes`. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. ### Option Tags from a Collection of Arbitrary Objects @@ -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 b1ca8da292..02ec024e5b 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: @@ -215,11 +215,7 @@ Open the `app/views/welcome/index.html.erb` file in your text editor and edit it ### Setting the Application Home Page -Now that we have made the controller and view, we need to tell Rails when we want Hello Rails! to show up. In our case, we want it to show up when we navigate to the root URL of our site, <http://localhost:3000>. At the moment, however, the "Welcome Aboard" smoke test is occupying that spot. - -To fix this, delete the `index.html` file located inside the `public` directory of the application. - -You need to do this because Rails will serve any static file in the `public` directory that matches a route in preference to any dynamic content you generate from the controllers. The `index.html` file is special: it will be served if a request comes in at the root route, e.g. <http://localhost:3000>. If another request such as <http://localhost:3000/welcome> happened, a static file at `public/welcome.html` would be served first, but only if it existed. +Now that we have made the controller and view, we need to tell Rails when we want Hello Rails! to show up. In our case, we want it to show up when we navigate to the root URL of our site, <http://localhost:3000>. At the moment, "Welcome Aboard" is occupying that spot. Next, you have to tell Rails where your actual home page is located. @@ -233,7 +229,6 @@ Blog::Application.routes.draw do # first created -> highest priority. # ... # You can have the root of your site routed with "root" - # just remember to delete public/index.html. # root to: "welcome#index" ``` @@ -558,7 +553,7 @@ 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 +As we did before, we need to add the `show` action in `app/controllers/posts_controller.rb` and its respective view. ```ruby diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 1131b7f245..2e61bea5ea 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -96,7 +96,7 @@ This means, that in the `:en` locale, the key _hello_ will map to the _Hello wor The I18n library will use **English** as a **default locale**, i.e. if you don't set a different locale, `:en` will be used for looking up translations. -NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize2](https://github.com/joshmh/globalize2/tree/master) may help you implement it. +NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize3](https://github.com/svenfuchs/globalize3) may help you implement it. The **translations load path** (`I18n.load_path`) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you. @@ -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. 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 829cbf2873..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: @@ -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 714c0b609e..14f23d4020 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. -------------------------------------------------------------------------------- @@ -471,7 +471,7 @@ resources :photos do end ``` -This will recognize `/photos/1/preview` with GET, and route to the `preview` action of `PhotosController`. It will also create the `preview_photo_url` and `preview_photo_path` helpers. +This will recognize `/photos/1/preview` with GET, and route to the `preview` action of `PhotosController`, with the resource id value passed in `params[:id]`. It will also create the `preview_photo_url` and `preview_photo_path` helpers. Within the block of member routes, each route name specifies the HTTP verb that it will recognize. You can use `get`, `patch`, `put`, `post`, or `delete` here. If you don't have multiple `member` routes, you can also pass `:on` to a route, eliminating the block: @@ -481,6 +481,8 @@ resources :photos do end ``` +You can leave out the `:on` option, this will create the same member route except that the resource id value will be available in `params[:photo_id]` instead of `params[:id]`. + #### Adding Collection Routes To add a route to the collection: @@ -733,12 +735,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 segments 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 @@ -797,7 +793,7 @@ root to: 'pages#main' root 'pages#main' # shortcut for the above ``` -You should put the `root` route at the top of the file, because it is the most popular route and should be matched first. You also need to delete the `public/index.html` file for the root route to take effect. +You should put the `root` route at the top of the file, because it is the most popular route and should be matched first. NOTE: The `root` route only routes `GET` requests to the action. diff --git a/guides/source/ruby_on_rails_guides_guidelines.md b/guides/source/ruby_on_rails_guides_guidelines.md index 2c3bc686ef..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 diff --git a/guides/source/security.md b/guides/source/security.md index 6c32a8ff5b..8096ea2383 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -374,141 +374,6 @@ The common admin interface works like this: it's located at www.example.com/admi * _Put the admin interface to a special sub-domain_ such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa. -Mass Assignment ---------------- - -WARNING: _Without any precautions `Model.new(params[:model]`) allows attackers to set -any database column's value._ - -The mass-assignment feature may become a problem, as it allows an attacker to set -any model's attributes by manipulating the hash passed to a model's `new()` method: - -```ruby -def signup - params[:user] # => {name:"ow3ned", admin:true} - @user = User.new(params[:user]) -end -``` - -Mass-assignment saves you much work, because you don't have to set each value -individually. Simply pass a hash to the `new` method, or `assign_attributes=` -a hash value, to set the model's attributes to the values in the hash. The -problem is that it is often used in conjunction with the parameters (params) -hash available in the controller, which may be manipulated by an attacker. -He may do so by changing the URL like this: - -``` -http://www.example.com/user/signup?user[name]=ow3ned&user[admin]=1 -``` - -This will set the following parameters in the controller: - -```ruby -params[:user] # => {name:"ow3ned", admin:true} -``` - -So if you create a new user using mass-assignment, it may be too easy to become -an administrator. - -Note that this vulnerability is not restricted to database columns. Any setter -method, unless explicitly protected, is accessible via the `attributes=` method. -In fact, this vulnerability is extended even further with the introduction of -nested mass assignment (and nested object forms) in Rails 2.3. The -`accepts_nested_attributes_for` declaration provides us the ability to extend -mass assignment to model associations (`has_many`, `has_one`, -`has_and_belongs_to_many`). For example: - -```ruby - class Person < ActiveRecord::Base - has_many :children - - accepts_nested_attributes_for :children - end - - class Child < ActiveRecord::Base - belongs_to :person - end -``` - -As a result, the vulnerability is extended beyond simply exposing column -assignment, allowing attackers the ability to create entirely new records -in referenced tables (children in this case). - -### Countermeasures - -To avoid this, Rails provides an interface for protecting attributes from -end-user assignment called Strong Parameters. This makes Action Controller -parameters forbidden until they have been whitelisted, so you will have to -make a conscious choice about which attributes to allow for mass assignment -and thus prevent accidentally exposing that which shouldn’t be exposed. - -NOTE. Before Strong Parameters arrived, mass-assignment protection was a -model's task provided by Active Model. This has been extracted to the -[ProtectedAttributes](https://github.com/rails/protected_attributes) -gem. In order to use `attr_accessible` and `attr_protected` helpers in -your models, you should add `protected_attributes` to your Gemfile. - -Why we moved mass-assignment protection out of the model and into -the controller? The whole point of the controller is to control the -flow between user and application, including authentication, authorization, -and, as part of that, access control. - -Strong Parameters provides two methods to the `params` hash to control -access to your attributes: `require` and `permit`. The former is used -to mark parameters as required and the latter limits which attributes -should be allowed for mass updating using the slice pattern. For example: - -```ruby -def signup - params[:user] - # => {name:"ow3ned", admin:true} - permitted_params = params.require(:user).permit(:name) - # => {name:"ow3ned"} - - @user = User.new(permitted_params) -end -``` - -In the example above, `require` is checking whether a `user` key is present or not -in the parameters, if it's not present, it'll raise an `ActionController::MissingParameter` -exception, which will be caught by `ActionController::Base` and turned into a -400 Bad Request reply. Then `permit` whitelists the attributes that should be -allowed for mass assignment. - -A good pattern to encapsulate the permissible parameters is to use a private method -since you'll be able to reuse the same permit list between different actions. - -```ruby -def signup - @user = User.new(user_params) - # ... -end - -def update - @user = User.find(params[:id] - @user.update_attributes!(user_params) - # ... -end - -private - def user_params - params.require(:user).permit(:name) - end -``` - -Also, you can specialize this method with per-user checking of permissible -attributes. - -```ruby -def user_params - if current_user.admin? - params.require(:user).permit(:name, :admin) - else - params.require(:user).permit(:name) - end -end -``` - User Management --------------- @@ -688,8 +553,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 attr_accessible instead of attr_protected. See the mass-assignment section for details +* Use before_action only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions. * Allow <strong> instead of removing <script> against Cross-Site Scripting (XSS). See below for details. * Don't try to correct user input by blacklists: * This will make the attack work: "<sc<script>ript>".gsub("<script>", "") 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/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index bdb4730cdc..b4a59fe3da 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -3,10 +3,6 @@ A Guide for Upgrading Ruby on Rails This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides. -After reading this guide, you will know: - --------------------------------------------------------------------------------- - General Advice -------------- @@ -31,7 +27,7 @@ Upgrading from Rails 3.2 to Rails 4.0 NOTE: This section is a work in progress. -If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting an update to Rails 4.0. +If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting one to Rails 4.0. The following changes are meant for upgrading your application to Rails 4.0. @@ -39,28 +35,21 @@ The following changes are meant for upgrading your application to Rails 4.0. Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must replace any plugins by extracting them to gems and adding them to 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`. -### Identity Map - -Rails 4.0 has removed the identity map from Active Record, due to [some inconsistencies with associations](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`. - ### Active Record -The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them. +* Rails 4.0 has removed the identity map from Active Record, due to [some inconsistencies with associations](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`. + +* The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them. -Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of rails new order was applied after previous defined order. But this is no long true. Check [Active Record Query guide](active_record_querying.html#ordering) for more information. +* Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of Rails, the new order was applied after the previously defined order. But this is no longer true. Check [Active Record Query guide](active_record_querying.html#ordering) for more information. -Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. Now you shouldn't use instance methods, it's deprecated. You must change them, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`. +* Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. Now you shouldn't use instance methods, it's deprecated. You must change them, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`. ### Active Model -Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. -Now when confirmation validations fail the error will be attached to -`:#{attribute}_confirmation` instead of `attribute`. +* Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail the error will be attached to `:#{attribute}_confirmation` instead of `attribute`. -Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default -value to `false`. Now, Active Model Serializers and Active Record objects have the -same default behaviour. This means that you can comment or remove the following option -in the `config/initializers/wrap_parameters.rb` file: +* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behaviour. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file: ```ruby # Disable root element in JSON by default. @@ -71,20 +60,17 @@ in the `config/initializers/wrap_parameters.rb` file: ### Action Pack -There is an upgrading cookie store `UpgradeSignatureToEncryptionCookieStore` which helps you upgrading apps that use `CookieStore` to the new default `EncryptedCookieStore`. To use this CookieStore set `Myapp::Application.config.session_store :upgrade_signature_to_encryption_cookie_store, key: '_myapp_session'` in `config/initializers/session_store.rb`. Additionally, add `Myapp::Application.config.secret_key_base = 'some secret'` in config/initializers/secret_token.rb (use `rake secret` to generate a value). Do not remove `Myapp::Application.config.secret_token = 'some secret'`. +* There is an upgrading cookie store `UpgradeSignatureToEncryptionCookieStore` which helps you upgrading apps that use `CookieStore` to the new default `EncryptedCookieStore`. To use this `CookieStore` set `Myapp::Application.config.session_store :upgrade_signature_to_encryption_cookie_store, key: '_myapp_session'` in `config/initializers/session_store.rb`. Additionally, add `Myapp::Application.config.secret_key_base = 'some secret'` in `config/initializers/secret_token.rb`. Do not remove `Myapp::Application.config.secret_token = 'some secret'`. -Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature. +* Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature. -Rails 4.0 has deprecated `ActionController::Base.page_cache_extension` option. Use -`ActionController::Base.default_static_extension` instead. +* Rails 4.0 has deprecated `ActionController::Base.page_cache_extension` option. Use `ActionController::Base.default_static_extension` instead. -Rails 4.0 has removed Action and Page caching from Action Pack. You will need to -add the `actionpack-action_caching` gem in order to use `caches_action` and -the `actionpack-page_caching` to use `caches_pages` in your controllers. +* Rails 4.0 has removed Action and Page caching from Action Pack. You will need to add the `actionpack-action_caching` gem in order to use `caches_action` and the `actionpack-page_caching` to use `caches_pages` in your controllers. -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 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`. -Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example: +* Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example: ```ruby get Rack::Utils.escape('こんにちは'), controller: 'welcome', action: 'index' @@ -98,11 +84,11 @@ get 'こんにちは', controller: 'welcome', action: 'index' ### Active Support -Rails 4.0 Removed the `j` alias for `ERB::Util#json_escape` since `j` is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`. +Rails 4.0 removes the `j` alias for `ERB::Util#json_escape` since `j` is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`. ### Helpers Loading Order -The loading order of helpers from more than one directory has changed in Rails 4.0. Previously, helpers from all directories were gathered and then sorted alphabetically. After upgrade to Rails 4.0 helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use `helpers_path` parameter, this change will only impact the way of loading helpers from engines. If you rely on the fact that particular helper from engine loads before or after another helper from application or another engine, you should check if correct methods are available after upgrade. If you would like to change order in which engines are loaded, you can use `config.railties_order=` method. +The order in which helpers from more than one directory are loaded has changed in Rails 4.0. Previously, they were gathered and then sorted alphabetically. After upgrading to Rails 4.0, helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use the `helpers_path` parameter, this change will only impact the way of loading helpers from engines. If you rely on the ordering, you should check if correct methods are available after upgrade. If you would like to change the order in which engines are loaded, you can use `config.railties_order=` method. Upgrading from Rails 3.1 to Rails 3.2 ------------------------------------- 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. ------------------------------------------------------------------------------- |