diff options
Diffstat (limited to 'guides/source')
-rw-r--r-- | guides/source/2_2_release_notes.textile | 4 | ||||
-rw-r--r-- | guides/source/2_3_release_notes.textile | 2 | ||||
-rw-r--r-- | guides/source/4_0_release_notes.textile | 272 | ||||
-rw-r--r-- | guides/source/action_mailer_basics.textile | 31 | ||||
-rw-r--r-- | guides/source/active_record_querying.textile | 28 | ||||
-rw-r--r-- | guides/source/configuring.textile | 2 | ||||
-rw-r--r-- | guides/source/contributing_to_ruby_on_rails.textile | 25 | ||||
-rw-r--r-- | guides/source/debugging_rails_applications.textile | 8 | ||||
-rw-r--r-- | guides/source/getting_started.textile | 4 | ||||
-rw-r--r-- | guides/source/i18n.textile | 2 | ||||
-rw-r--r-- | guides/source/migrations.textile | 47 | ||||
-rw-r--r-- | guides/source/performance_testing.textile | 6 | ||||
-rw-r--r-- | guides/source/plugins.textile | 2 | ||||
-rw-r--r-- | guides/source/routing.textile | 26 | ||||
-rw-r--r-- | guides/source/security.textile | 2 |
15 files changed, 396 insertions, 65 deletions
diff --git a/guides/source/2_2_release_notes.textile b/guides/source/2_2_release_notes.textile index 3a0f2efbaf..eb4b32329b 100644 --- a/guides/source/2_2_release_notes.textile +++ b/guides/source/2_2_release_notes.textile @@ -118,9 +118,9 @@ h4. Transactional Migrations Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter. -* Lead Contributor: "Adam Wiggins":http://adam.blog.heroku.com/ +* Lead Contributor: "Adam Wiggins":http://adam.heroku.com/ * More information: -** "DDL Transactions":http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/ +** "DDL Transactions":http://adam.heroku.com/past/2008/9/3/ddl_transactions/ ** "A major milestone for DB2 on Rails":http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/ h4. Connection Pooling diff --git a/guides/source/2_3_release_notes.textile b/guides/source/2_3_release_notes.textile index 15abba66ab..36f425574b 100644 --- a/guides/source/2_3_release_notes.textile +++ b/guides/source/2_3_release_notes.textile @@ -561,7 +561,7 @@ This will layer the changes from the template on top of whatever code the projec h4. Quieter Backtraces -Building on Thoughtbot's "Quiet Backtrace":http://www.thoughtbot.com/projects/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace. +Building on Thoughtbot's "Quiet Backtrace":https://github.com/thoughtbot/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace. h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload diff --git a/guides/source/4_0_release_notes.textile b/guides/source/4_0_release_notes.textile index 23c5220c24..895372ba63 100644 --- a/guides/source/4_0_release_notes.textile +++ b/guides/source/4_0_release_notes.textile @@ -64,6 +64,16 @@ h3. Documentation h3. Railties +* Allow scaffold/model/migration generators to accept a <tt>polymorphic</tt> modifier for <tt>references</tt>/<tt>belongs_to</tt>, for instance + +<shell> +rails g model Product supplier:references{polymorphic} +</shell> + +will generate the model with <tt>belongs_to :supplier, polymorphic: true</tt> association and appropriate migration. + +* Set <tt>config.active_record.migration_error</tt> to <tt>:page_load</tt> for development. + * Add runner to <tt>Rails::Railtie</tt> as a hook called just after runner starts. * Add <tt>/rails/info/routes</tt> path which displays the same information as +rake routes+. @@ -102,12 +112,42 @@ h4(#railties_deprecations). Deprecations h3. Action Mailer -* No changes. +* Allow to set default Action Mailer options via <tt>config.action_mailer.default_options=</tt>. + +* Raise an <tt>ActionView::MissingTemplate</tt> exception when no implicit template could be found. + +* Asynchronously send messages via the Rails Queue. h3. Action Pack h4. Action Controller +* Add <tt>ActionController::Flash.add_flash_types</tt> method to allow people to register their own flash types. e.g.: + +<ruby> +class ApplicationController + add_flash_types :error, :warning +end +</ruby> + +If you add the above code, you can use <tt><%= error %></tt> in an erb, and <tt>redirect_to /foo, :error => 'message'</tt> in a controller. + +* Remove Active Model dependency from Action Pack. + +* Support unicode characters in routes. Route will be automatically escaped, so instead of manually escaping: + +<ruby> +get Rack::Utils.escape('こんにちは') => 'home#index' +</ruby> + +You just have to write the unicode route: + +<ruby> +get 'こんにちは' => 'home#index' +</ruby> + +* Return proper format on exceptions. + * Extracted redirect logic from <tt>ActionController::ForceSSL::ClassMethods.force_ssl</tt> into <tt>ActionController::ForceSSL#force_ssl_redirect</tt>. * URL path parameters with invalid encoding now raise <tt>ActionController::BadRequest</tt>. @@ -156,6 +196,10 @@ h5(#actioncontroller_deprecations). Deprecations h4. Action Dispatch +* Show routes in exception page while debugging a <tt>RoutingError</tt> in development. + +* Include <tt>mounted_helpers</tt> (helpers for accessing mounted engines) in <tt>ActionDispatch::IntegrationTest</tt> by default. + * Added <tt>ActionDispatch::SSL</tt> middleware that when included force all the requests to be under HTTPS protocol. * Copy literal route constraints to defaults so that url generation know about them. The copied constraints are <tt>:protocol</tt>, <tt>:subdomain</tt>, <tt>:domain</tt>, <tt>:host</tt> and <tt>:port</tt>. @@ -179,12 +223,14 @@ If <tt>:patch</tt> is the default verb for updates, edits are tunneled as <tt>PA * Turn off verbose mode of <tt>rack-cache</tt>, we still have <tt>X-Rack-Cache</tt> to check that info. -* Include mounted_helpers (helpers for accessing mounted engines) in <tt>ActionDispatch::IntegrationTest</tt> by default. - h5(#actiondispatch_deprecations). Deprecations h4. Action View +* Remove Active Model dependency from Action Pack. + +* Allow to use <tt>mounted_helpers</tt> (helpers for accessing mounted engines) in <tt>ActionView::TestCase</tt>. + * Make current object and counter (when it applies) variables accessible when rendering templates with <tt>:object</tt> or <tt>:collection</tt>. * Allow to lazy load +default_form_builder+ by passing a string instead of a constant. @@ -205,8 +251,6 @@ h4. Action View * Removed old +text_helper+ apis for +highlight+, +excerpt+ and +word_wrap+. -* Allow to use mounted_helpers (helpers for accessing mounted engines) in <tt>ActionView::TestCase</tt>. - * Remove the leading \n added by textarea on +assert_select+. * Changed default value for <tt>config.action_view.embed_authenticity_token_in_remote_forms</tt> to false. This change breaks remote forms that need to work also without JavaScript, so if you need such behavior, you can either set it to true or explicitly pass <tt>:authenticity_token => true</tt> in form options. @@ -299,6 +343,146 @@ Moved into a separate gem <tt>sprockets-rails</tt>. h3. Active Record +* Add <tt>add_reference</tt> and <tt>remove_reference</tt> schema statements. Aliases, <tt>add_belongs_to</tt> and <tt>remove_belongs_to</tt> are acceptable. References are reversible. + +<ruby> +# Create a user_id column +add_reference(:products, :user) + +# Create a supplier_id, supplier_type columns and appropriate index +add_reference(:products, :supplier, polymorphic: true, index: true) + +# Remove polymorphic reference +remove_reference(:products, :supplier, polymorphic: true) +</ruby> + + +* Add <tt>:default</tt> and <tt>:null</tt> options to <tt>column_exists?</tt>. + +<ruby> +column_exists?(:testings, :taggable_id, :integer, null: false) +column_exists?(:testings, :taggable_type, :string, default: 'Photo') +</ruby> + +* <tt>ActiveRecord::Relation#inspect</tt> now makes it clear that you are dealing with a <tt>Relation</tt> object rather than an array: + +<ruby> +User.where(:age => 30).inspect +# => <ActiveRecord::Relation [#<User ...>, #<User ...>]> + +User.where(:age => 30).to_a.inspect +# => [#<User ...>, #<User ...>] +</ruby> + +if more than 10 items are returned by the relation, inspect will only show the first 10 followed by ellipsis. + +* Add <tt>:collation</tt> and <tt>:ctype</tt> support to PostgreSQL. These are available for PostgreSQL 8.4 or later. + +<yaml> +development: + adapter: postgresql + host: localhost + database: rails_development + username: foo + password: bar + encoding: UTF8 + collation: ja_JP.UTF8 + ctype: ja_JP.UTF8 +</yaml> + +* <tt>FinderMethods#exists?</tt> now returns <tt>false</tt> with the <tt>false</tt> argument. + +* Added support for specifying the precision of a timestamp in the postgresql adapter. So, instead of having to incorrectly specify the precision using the <tt>:limit</tt> option, you may use <tt>:precision</tt>, as intended. For example, in a migration: + +<ruby> +def change + create_table :foobars do |t| + t.timestamps :precision => 0 + end +end +</ruby> + +* Allow <tt>ActiveRecord::Relation#pluck</tt> to accept multiple columns. Returns an array of arrays containing the typecasted values: + +<ruby> +Person.pluck(:id, :name) +# SELECT people.id, people.name FROM people +# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']] +</ruby> + +* Improve the derivation of HABTM join table name to take account of nesting. It now takes the table names of the two models, sorts them lexically and then joins them, stripping any common prefix from the second table name. Some examples: + +<plain> +Top level models (Category <=> Product) +Old: categories_products +New: categories_products + +Top level models with a global table_name_prefix (Category <=> Product) +Old: site_categories_products +New: site_categories_products + +Nested models in a module without a table_name_prefix method (Admin::Category <=> Admin::Product) +Old: categories_products +New: categories_products + +Nested models in a module with a table_name_prefix method (Admin::Category <=> Admin::Product) +Old: categories_products +New: admin_categories_products + +Nested models in a parent model (Catalog::Category <=> Catalog::Product) +Old: categories_products +New: catalog_categories_products + +Nested models in different parent models (Catalog::Category <=> Content::Page) +Old: categories_pages +New: catalog_categories_content_pages +</plain> + +* Move HABTM validity checks to <tt>ActiveRecord::Reflection</tt>. One side effect of this is to move when the exceptions are raised from the point of declaration to when the association is built. This is consistant with other association validity checks. + +* Added <tt>stored_attributes</tt> hash which contains the attributes stored using <tt>ActiveRecord::Store</tt>. This allows you to retrieve the list of attributes you've defined. + +<ruby> +class User < ActiveRecord::Base + store :settings, accessors: [:color, :homepage] +end + +User.stored_attributes[:settings] # [:color, :homepage] +</ruby> + +* <tt>composed_of</tt> was removed. You'll have to write your own accessor and mutator methods if you'd like to use value objects to represent some portion of your models. So, instead of: + +<ruby> +class Person < ActiveRecord::Base + composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ] +end +</ruby> + +you could write something like this: + +<ruby> +def address + @address ||= Address.new(address_street, address_city) +end + +def address=(address) + self[:address_street] = @address.street + self[:address_city] = @address.city + + @address = address +end +</ruby> + +* PostgreSQL default log level is now 'warning', to bypass the noisy notice messages. You can change the log level using the <tt>min_messages</tt> option available in your <tt>config/database.yml</tt>. + +* Add uuid datatype support to PostgreSQL adapter. + +* <tt>update_attribute</tt> has been removed. Use <tt>update_column</tt> if you want to bypass mass-assignment protection, validations, callbacks, and touching of updated_at. Otherwise please use <tt>update_attributes</tt>. + +* Added <tt>ActiveRecord::Migration.check_pending!</tt> that raises an error if migrations are pending. + +* Added <tt>#destroy!</tt> which acts like <tt>#destroy</tt> but will raise an <tt>ActiveRecord::RecordNotDestroyed</tt> exception instead of returning <tt>false</tt>. + * Allow blocks for count with <tt>ActiveRecord::Relation</tt>, to work similar as <tt>Array#count</tt>: <tt>Person.where("age > 26").count { |person| person.gender == 'female' }</tt> * Added support to <tt>CollectionAssociation#delete</tt> for passing fixnum or string values as record ids. This finds the records responding to the ids and deletes them. @@ -355,7 +539,7 @@ Post.find_by! name: 'Spartacus' * Added <tt>ActiveRecord::Base#slice</tt> to return a hash of the given methods with their names as keys and returned values as values. -* Remove IdentityMap - IdentityMap has never graduated to be an "enabled-by-default" feature, due to some inconsistencies with associations, as described in this commit: https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. Hence the removal from the codebase, until such issues are fixed. +* Remove IdentityMap - IdentityMap has never graduated to be an "enabled-by-default" feature, due to some inconsistencies with associations, as described in this "commit":https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. Hence the removal from the codebase, until such issues are fixed. * Added a feature to dump/load internal state of +SchemaCache+ instance because we want to boot more quickly when we have many models. @@ -475,27 +659,37 @@ The code to implement the deprecated features has been moved out to the +active_ Don't use this: - scope :red, where(color: 'red') - default_scope where(color: 'red') +<ruby> +scope :red, where(color: 'red') +default_scope where(color: 'red') +</ruby> Use this: - scope :red, -> { where(color: 'red') } - default_scope { where(color: 'red') } +<ruby> +scope :red, -> { where(color: 'red') } +default_scope { where(color: 'red') } +</ruby> The former has numerous issues. It is a common newbie gotcha to do the following: - scope :recent, where(published_at: Time.now - 2.weeks) +<ruby> +scope :recent, where(published_at: Time.now - 2.weeks) +</ruby> Or a more subtle variant: - scope :recent, -> { where(published_at: Time.now - 2.weeks) } - scope :recent_red, recent.where(color: 'red') +<ruby> +scope :recent, -> { where(published_at: Time.now - 2.weeks) } +scope :recent_red, recent.where(color: 'red') +</ruby> Eager scopes are also very complex to implement within Active Record, and there are still bugs. For example, the following does not do what you expect: - scope :remove_conditions, except(:where) - where(...).remove_conditions # => still has conditions +<ruby> +scope :remove_conditions, except(:where) +where(...).remove_conditions # => still has conditions +</ruby> * Added deprecation for the :dependent => :restrict association option. @@ -507,6 +701,32 @@ The code to implement the deprecated features has been moved out to the +active_ h3. Active Model +* Changed <tt>AM::Serializers::JSON.include_root_in_json</tt> default value to false. Now, AM Serializers and AR objects have the same default behaviour. + +<ruby> +class User < ActiveRecord::Base; end + +class Person + include ActiveModel::Model + include ActiveModel::AttributeMethods + include ActiveModel::Serializers::JSON + + attr_accessor :name, :age + + def attributes + instance_values + end +end + +user.as_json +=> {"id"=>1, "name"=>"Konata Izumi", "age"=>16, "awesome"=>true} +# root is not included + +person.as_json +=> {"name"=>"Francesco", "age"=>22} +# root is not included +</ruby> + * Passing false hash values to +validates+ will no longer enable the corresponding validators. * +ConfirmationValidator+ error messages will attach to <tt>:#{attribute}_confirmation</tt> instead of +attribute+. @@ -521,10 +741,28 @@ h4(#activemodel_deprecations). Deprecations h3. Active Resource -* Active Resource is removed from Rails 4.0 and is now a separate gem. TODO: put a link to the gem here. +* Active Resource is removed from Rails 4.0 and is now a separate "gem":https://github.com/rails/activeresource. h3. Active Support +* <tt>Time#change</tt> now works with time values with offsets other than UTC or the local time zone. + +* Add <tt>Time#prev_quarter</tt> and <tt>Time#next_quarter</tt> short-hands for <tt>months_ago(3)</tt> and <tt>months_since(3)</tt>. + +* Remove obsolete and unused <tt>require_association</tt> method from dependencies. + +* Add <tt>:instance_accessor</tt> option for <tt>config_accessor</tt>. + +<ruby> +class User + include ActiveSupport::Configurable + config_accessor :allowed_access, instance_accessor: false +end + +User.new.allowed_access = true # => NoMethodError +User.new.allowed_access # => NoMethodError +</ruby> + * <tt>ActionView::Helpers::NumberHelper</tt> methods have been moved to <tt>ActiveSupport::NumberHelper</tt> and are now available via <tt>Numeric#to_s</tt>. * <tt>Numeric#to_s</tt> now accepts the formatting options :phone, :currency, :percentage, :delimited, :rounded, :human, and :human_size. @@ -575,6 +813,8 @@ h3. Active Support h4(#activesupport_deprecations). Deprecations +* <tt>ActiveSupport::Callbacks</tt>: deprecate usage of filter object with <tt>#before</tt> and <tt>#after</tt> methods as <tt>around</tt> callback. + * <tt>BufferedLogger</tt> is deprecated. Use <tt>ActiveSupport::Logger</tt> or the +logger+ from Ruby stdlib. * Deprecates the compatibility method <tt>Module#local_constant_names</tt> and use <tt>Module#local_constants</tt> instead (which returns symbols). diff --git a/guides/source/action_mailer_basics.textile b/guides/source/action_mailer_basics.textile index ebe774fbef..7c61cc4a8d 100644 --- a/guides/source/action_mailer_basics.textile +++ b/guides/source/action_mailer_basics.textile @@ -457,6 +457,7 @@ The following configuration options are best made in one of the environment file |+delivery_method+|Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, <tt>:file</tt> and <tt>:test</tt>.| |+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.| +|+async+|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to <tt>Rails.queue</tt> for processing.| h4. Example Action Mailer Configuration @@ -514,3 +515,33 @@ end </ruby> In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect. + +h3. Asynchronous + +You can turn on application-wide asynchronous message sending by adding to your <tt>config/application.rb</tt> file: + +<ruby> +config.action_mailer.async = true +</ruby> + +Alternatively you can turn on async within specific mailers: + +<ruby> +class WelcomeMailer < ActionMailer::Base + self.async = true +end +</ruby> + +h4. Custom Queues + +If you need a different queue than <tt>Rails.queue</tt> for your mailer you can override <tt>ActionMailer::Base#queue</tt>: + +<ruby> +class WelcomeMailer < ActionMailer::Base + def queue + MyQueue.new + end +end +</ruby> + +Your custom queue should expect a job that responds to <tt>#run</tt>. diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 101988c59e..9863d16fda 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -12,8 +12,6 @@ This guide covers different ways to retrieve data from the database using Active endprologue. -WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails. - If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases. Code examples throughout this guide will refer to one or more of the following models: @@ -53,20 +51,26 @@ h3. Retrieving Objects from the Database To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL. The methods are: -* +where+ -* +select+ +* +bind+ +* +create_with+ +* +extending+ +* +from+ * +group+ -* +order+ -* +reorder+ -* +reverse_order+ -* +limit+ -* +offset+ -* +joins+ +* +having+ * +includes+ +* +joins+ +* +limit+ * +lock+ +* +offset+ +* +order+ +* +none+ * +readonly+ -* +from+ -* +having+ +* +references+ +* +reorder+ +* +reverse_order+ +* +select+ +* +uniq+ +* +where+ All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>. diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index af46538bf5..cd9aab4892 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -424,7 +424,7 @@ There are a number of settings available on +config.action_mailer+: * +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing. -* +config.action_mailer.default+ configures Action Mailer defaults. These default to: +* +config.action_mailer.default_options+ configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to: <ruby> :mime_version => "1.0", :charset => "UTF-8", diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile index 1dadce2083..fd5e2b28c0 100644 --- a/guides/source/contributing_to_ruby_on_rails.textile +++ b/guides/source/contributing_to_ruby_on_rails.textile @@ -66,12 +66,26 @@ Install first libxml2 and libxslt together with their development files for Noko $ sudo apt-get install libxml2 libxml2-dev libxslt1-dev </shell> +If you are on Fedora or CentOS, you can run + +<shell> +$ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel +</shell> + +If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions "here":http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos . + Also, SQLite3 and its development files for the +sqlite3-ruby+ gem -- in Ubuntu you're done with just <shell> $ sudo apt-get install sqlite3 libsqlite3-dev </shell> +And if you are on Fedora or CentOS, you're done with + +<shell> +$ sudo yum install sqlite3 sqlite3-devel +</shell> + Get a recent version of "Bundler":http://gembundler.com/: <shell> @@ -150,6 +164,13 @@ $ sudo apt-get install mysql-server libmysqlclient15-dev $ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev </shell> +On Fedora or CentOS, just run: + +<shell> +$ sudo yum install mysql-server mysql-devel +$ sudo yum install postgresql-server postgresql-devel +</shell> + After that run: <shell> @@ -172,7 +193,7 @@ and create the test databases: <shell> $ cd activerecord -$ rake mysql:build_databases +$ bundle exec rake mysql:build_databases </shell> PostgreSQL's authentication works differently. A simple way to set up the development environment for example is to run with your development account @@ -185,7 +206,7 @@ and then create the test databases with <shell> $ cd activerecord -$ rake postgresql:build_databases +$ bundle exec rake postgresql:build_databases </shell> NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index 0802a2db26..667f2d2140 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -102,7 +102,7 @@ It can also be useful to save information to log files at runtime. Rails maintai h4. What is the Logger? -Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish. +Rails makes use of the +ActiveSupport::BufferedLogger+ class to write log information. You can also substitute another logger such as +Log4r+ if you wish. You can specify an alternative logger in your +environment.rb+ or any environment file: @@ -626,7 +626,7 @@ In this section, you will learn how to find and fix such leaks by using tools su h4. BleakHouse -"BleakHouse":https://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks. +"BleakHouse":https://github.com/evan/bleak_house/ is a library for finding memory leaks. If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap. @@ -675,7 +675,7 @@ To analyze it, just run the listed command. The top 20 leakiest lines will be li This way you can find where your application is leaking memory and fix it. -If "BleakHouse":https://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further. +If "BleakHouse":https://github.com/evan/bleak_house/ doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further. h4. Valgrind @@ -708,4 +708,4 @@ h3. References * "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html * "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/ * "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging -* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html +* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/ diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 897327a888..07419d11b4 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -900,7 +900,7 @@ end </ruby> The new method, +update_attributes+, is used when you want to update a record -that already exists, and it accepts an hash containing the attributes +that already exists, and it accepts a hash containing the attributes that you want to update. As before, if there was an error updating the post we want to show the form back to the user. @@ -1185,7 +1185,7 @@ delete "posts/:id" => "posts#destroy" That's a lot to type for covering a single *resource*. Fortunately, Rails provides a +resources+ method which can be used to declare a -standard REST resource. Here's how +config/routes/rb+ looks after the +standard REST resource. Here's how +config/routes.rb+ looks after the cleanup: <ruby> diff --git a/guides/source/i18n.textile b/guides/source/i18n.textile index ee7176a6c8..8ad6ee4b73 100644 --- a/guides/source/i18n.textile +++ b/guides/source/i18n.textile @@ -220,7 +220,7 @@ Every helper method dependent on +url_for+ (e.g. helpers for named routes like + You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this. -You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Dutch locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+path_prefix+":http://api.rubyonrails.org/classes/ActionController/Resources.html#M000354 option in this way: +You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Dutch locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+scoping+":http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html option in this way: <ruby> # config/routes.rb diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index 342b5a4d57..06e85e5914 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -111,6 +111,7 @@ Active Record provides methods that perform common data definition tasks in a database independent way (you'll read about them in detail later): * +add_column+ +* +add_reference+ * +add_index+ * +change_column+ * +change_table+ @@ -120,6 +121,7 @@ database independent way (you'll read about them in detail later): * +remove_column+ * +remove_index+ * +rename_column+ +* +remove_reference+ If you need to perform tasks specific to your database (for example create a "foreign key":#active-record-and-referential-integrity constraint) then the @@ -332,6 +334,51 @@ NOTE: The generated migration file for destructive migrations will still be old-style using the +up+ and +down+ methods. This is because Rails needs to know the original data types defined when you made the original changes. +Also the generator accepts column type as +references+(also available as +belongs_to+), for instance + +<shell> +$ rails generate migration AddUserRefToProducts user:references +</shell> + +generates + +<ruby> +class AddUserRefToProducts < ActiveRecord::Migration + def change + add_reference :products, :user, :index => true + end +end +</ruby> + +This migration will create a user_id column and appropriate index. + +h4. Supported type modifiers + +You can also specify some options just after the field type between curly braces. You can use the +following modifiers: + +* +limit+ Sets the maximum size of the +string/text/binary/integer+ fields +* +precision+ Defines the precision for the +decimal+ fields +* +scale+ Defines the scale for the +decimal+ fields +* +polymorphic+ Adds a +type+ column for +belongs_to+ associations + +For instance running + +<shell> +$ rails generate migration AddDetailsToProducts price:decimal{5,2} supplier:references{polymorphic} +</shell> + +will produce a migration that looks like this + +<ruby> +class AddDetailsToProducts < ActiveRecord::Migration + def change + add_column :products, :price, :precision => 5, :scale => 2 + add_reference :products, :user, :polymorphic => true, :index => true + end +end +</ruby> + h3. Writing a Migration Once you have created your migration using one of the generators it's time to diff --git a/guides/source/performance_testing.textile b/guides/source/performance_testing.textile index 958b13cd9e..982fd1b070 100644 --- a/guides/source/performance_testing.textile +++ b/guides/source/performance_testing.textile @@ -524,11 +524,11 @@ Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveRecord/B h4. Controller -Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715 +Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html <ruby> def process_projects - self.class.benchmark("Processing projects") do + benchmark("Processing projects") do Project.process(params[:project_ids]) Project.update_cached_projects end @@ -539,7 +539,7 @@ NOTE: +benchmark+ is a class method inside controllers h4. View -And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715: +And in "views":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html: <erb> <% benchmark("Showing projects partial") do %> diff --git a/guides/source/plugins.textile b/guides/source/plugins.textile index 95e38db483..9001857a5f 100644 --- a/guides/source/plugins.textile +++ b/guides/source/plugins.textile @@ -427,4 +427,4 @@ h4. References * "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md * "Using Gemspecs As Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/ * "Gemspec Reference":http://docs.rubygems.org/read/chapter/20 -* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +* "GemPlugins":http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins diff --git a/guides/source/routing.textile b/guides/source/routing.textile index dae25853cd..cffbf9bec4 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -32,7 +32,13 @@ the request is dispatched to the +patients+ controller's +show+ action with <tt> h4. Generating Paths and URLs from Code -You can also generate paths and URLs. If your application contains this code: +You can also generate paths and URLs. If the route above is modified to be + +<ruby> +get "/patients/:id" => "patients#show", :as => "patient" +</ruby> + +If your application contains this code: <ruby> @patient = Patient.find(17) @@ -845,24 +851,6 @@ end This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+. -h3. Breaking Up a Large Route File - -If you have a large route file that you would like to break up into multiple files, you can use the +#draw+ method in your router: - -<ruby> -draw :admin -</ruby> - -Then, create a file called +config/routes/admin.rb+. Name the file the same as the symbol passed to the +draw+ method. You can then use the normal routing DSL inside that file: - -<ruby> -# in config/routes/admin.rb - -namespace :admin do - resources :posts -end -</ruby> - h3. Inspecting and Testing Routes Rails offers facilities for inspecting and testing your routes. diff --git a/guides/source/security.textile b/guides/source/security.textile index 626d6fa508..8879122b66 100644 --- a/guides/source/security.textile +++ b/guides/source/security.textile @@ -851,7 +851,7 @@ Network traffic is mostly based on the limited Western alphabet, so new characte &#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;> </html> -This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":http://www.businessinfo.co.uk/labs/hackvertor/hackvertor.php. Rails' sanitize() method does a good job to fend off encoding attacks. +This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":https://hackvertor.co.uk/public. Rails' sanitize() method does a good job to fend off encoding attacks. h5. Examples from the Underground |