aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--Gemfile.lock83
-rw-r--r--Rakefile1
-rw-r--r--actionmailer/test/i18n_with_controller_test.rb1
-rw-r--r--actionpack/CHANGELOG.md19
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb2
-rw-r--r--actionpack/lib/action_controller/metal.rb1
-rw-r--r--actionpack/lib/action_controller/metal/exceptions.rb8
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb8
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb1
-rw-r--r--actionpack/lib/action_controller/test_case.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb11
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb5
-rw-r--r--actionpack/lib/action_dispatch/middleware/reloader.rb2
-rw-r--r--actionpack/lib/action_dispatch/request/utils.rb15
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb1
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb1
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb10
-rw-r--r--actionpack/test/controller/integration_test.rb30
-rw-r--r--actionpack/test/controller/live_stream_test.rb6
-rw-r--r--actionpack/test/controller/new_base/render_text_test.rb1
-rw-r--r--actionpack/test/controller/parameters/mutators_test.rb4
-rw-r--r--actionpack/test/controller/render_test.rb4
-rw-r--r--actionpack/test/controller/test_case_test.rb2
-rw-r--r--actionpack/test/dispatch/request_test.rb30
-rw-r--r--actionpack/test/dispatch/response_test.rb2
-rw-r--r--actionpack/test/dispatch/routing/concerns_test.rb2
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb4
-rw-r--r--actionpack/test/dispatch/static_test.rb2
-rw-r--r--actionview/CHANGELOG.md5
-rw-r--r--actionview/lib/action_view/helpers/tags/collection_helpers.rb2
-rw-r--r--actionview/test/actionpack/abstract/render_test.rb1
-rw-r--r--actionview/test/fixtures/digestor/comments/_comment.html.erb2
-rw-r--r--actionview/test/template/form_collections_helper_test.rb11
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb23
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb38
-rw-r--r--activerecord/CHANGELOG.md115
-rw-r--r--activerecord/lib/active_record/associations.rb24
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb2
-rw-r--r--activerecord/lib/active_record/associations/builder/has_many.rb2
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/join_dependency.rb14
-rw-r--r--activerecord/lib/active_record/associations/preloader.rb15
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb72
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb2
-rw-r--r--activerecord/lib/active_record/autosave_association.rb12
-rw-r--r--activerecord/lib/active_record/callbacks.rb5
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb19
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb85
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb81
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb1
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb44
-rw-r--r--activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb22
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb7
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb12
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb15
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb30
-rw-r--r--activerecord/lib/active_record/core.rb2
-rw-r--r--activerecord/lib/active_record/explain_subscriber.rb2
-rw-r--r--activerecord/lib/active_record/integration.rb4
-rw-r--r--activerecord/lib/active_record/migration.rb66
-rw-r--r--activerecord/lib/active_record/railties/databases.rake2
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb19
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb4
-rw-r--r--activerecord/lib/active_record/relation/where_clause_factory.rb4
-rw-r--r--activerecord/lib/active_record/scoping/default.rb2
-rw-r--r--activerecord/lib/active_record/tasks/database_tasks.rb6
-rw-r--r--activerecord/lib/active_record/tasks/sqlite_database_tasks.rb6
-rw-r--r--activerecord/lib/rails/generators/active_record/migration.rb7
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/migration_generator.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/model/model_generator.rb11
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb9
-rw-r--r--activerecord/test/cases/adapters/mysql/sp_test.rb24
-rw-r--r--activerecord/test/cases/adapters/mysql/sql_types_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/sp_test.rb29
-rw-r--r--activerecord/test/cases/adapters/mysql2/sql_types_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb5
-rw-r--r--activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb41
-rw-r--r--activerecord/test/cases/associations/eager_test.rb12
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb19
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb20
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb8
-rw-r--r--activerecord/test/cases/autosave_association_test.rb36
-rw-r--r--activerecord/test/cases/cache_key_test.rb25
-rw-r--r--activerecord/test/cases/calculations_test.rb76
-rw-r--r--activerecord/test/cases/collection_cache_key_test.rb2
-rw-r--r--activerecord/test/cases/finder_test.rb6
-rw-r--r--activerecord/test/cases/helper.rb2
-rw-r--r--activerecord/test/cases/integration_test.rb18
-rw-r--r--activerecord/test/cases/relation_test.rb11
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb2
-rw-r--r--activerecord/test/cases/tasks/postgresql_rake_test.rb2
-rw-r--r--activerecord/test/cases/tasks/sqlite_rake_test.rb2
-rw-r--r--activerecord/test/fixtures/content.yml3
-rw-r--r--activerecord/test/fixtures/content_positions.yml3
-rw-r--r--activerecord/test/models/company.rb1
-rw-r--r--activerecord/test/models/content.rb40
-rw-r--r--activerecord/test/models/developer.rb2
-rw-r--r--activerecord/test/models/guitar.rb4
-rw-r--r--activerecord/test/models/mentor.rb3
-rw-r--r--activerecord/test/models/project.rb1
-rw-r--r--activerecord/test/models/tuning_peg.rb4
-rw-r--r--activerecord/test/schema/mysql2_specific_schema.rb13
-rw-r--r--activerecord/test/schema/mysql_specific_schema.rb6
-rw-r--r--activerecord/test/schema/schema.rb23
-rw-r--r--activesupport/CHANGELOG.md35
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb7
-rw-r--r--activesupport/lib/active_support/callbacks.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal/conversions.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/integer/time.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/anonymous.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/module/remove_method.rb20
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/conversions.rb37
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb1
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb8
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_human_converter.rb6
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb6
-rw-r--r--activesupport/test/caching_test.rb5
-rw-r--r--activesupport/test/core_ext/module/remove_method_test.rb38
-rw-r--r--activesupport/test/core_ext/module_test.rb15
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb10
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb1
-rw-r--r--activesupport/test/multibyte_chars_test.rb12
-rw-r--r--activesupport/test/number_helper_test.rb2
-rw-r--r--activesupport/test/tagged_logging_test.rb12
-rw-r--r--guides/source/active_record_validations.md22
-rw-r--r--guides/source/active_support_core_extensions.md16
-rw-r--r--guides/source/active_support_instrumentation.md1
-rw-r--r--guides/source/api_documentation_guidelines.md7
-rw-r--r--guides/source/asset_pipeline.md2
-rw-r--r--guides/source/configuring.md8
-rw-r--r--guides/source/engines.md2
-rw-r--r--guides/source/initialization.md3
-rw-r--r--guides/source/routing.md2
-rw-r--r--railties/lib/rails/application.rb3
-rw-r--r--railties/lib/rails/console/helpers.rb2
-rw-r--r--railties/lib/rails/engine/configuration.rb2
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb2
-rw-r--r--railties/test/application/configuration_test.rb13
-rw-r--r--railties/test/application/middleware/exceptions_test.rb6
-rw-r--r--railties/test/application/rake/dbs_test.rb52
-rw-r--r--railties/test/generators/migration_generator_test.rb9
-rw-r--r--railties/test/generators/model_generator_test.rb9
-rw-r--r--railties/test/generators/plugin_generator_test.rb13
155 files changed, 1452 insertions, 533 deletions
diff --git a/.travis.yml b/.travis.yml
index 5d4a9e9c67..46be91d18e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -13,8 +13,6 @@ before_script:
- bundle update
cache: bundler
env:
- global:
- - JRUBY_OPTS='-J-Xmx1024M'
matrix:
- "GEM=railties"
- "GEM=ap"
diff --git a/Gemfile.lock b/Gemfile.lock
index 1797355194..58d2941170 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -21,7 +21,7 @@ GIT
GIT
remote: git://github.com/mikel/mail.git
- revision: 64ef1a12efcdda53fd63e1456c2c564044bf82ce
+ revision: 9c313a401729b9aa9177878836829a61adf67b54
branch: master
specs:
mail (2.6.3.edge)
@@ -29,7 +29,7 @@ GIT
GIT
remote: git://github.com/rack/rack.git
- revision: e836fad64ba3a79f8169ef44aa97b7004fca5e86
+ revision: 35599cfc2751e0ee611c0ff799924b8e7fe0c0b4
branch: master
specs:
rack (2.0.0.alpha)
@@ -37,7 +37,7 @@ GIT
GIT
remote: git://github.com/rails/arel.git
- revision: 77ec13b46af2926bfcfc3073685711c874b0d272
+ revision: 3c429c5d86e9e2201c2a35d934ca6a8911c18e69
branch: master
specs:
arel (7.0.0.alpha)
@@ -62,7 +62,7 @@ GIT
GIT
remote: git://github.com/rails/sass-rails.git
- revision: a3b25261a3d31ed9ff5dd6e841b777790fc86c55
+ revision: 6e4eee736bcbfa5b2962467673c7a51abf434c67
branch: master
specs:
sass-rails (6.0.0)
@@ -73,7 +73,7 @@ GIT
GIT
remote: git://github.com/rails/sprockets-rails.git
- revision: 77098c5acd9f27613875097ce6587aff9d871d7f
+ revision: 93a45b1c463a063ec7cf4d160107b67aa3db7a1a
branch: master
specs:
sprockets-rails (3.0.0.beta3)
@@ -83,15 +83,15 @@ GIT
GIT
remote: git://github.com/rails/sprockets.git
- revision: edae5cdfa241b0fb0fcb756b25cd561c3d8b7f29
+ revision: 5a77f8b007b8ec61edd783c48baf9d971f1c684d
branch: master
specs:
sprockets (4.0.0)
- rack (> 1, < 3)
+ rack (>= 1, < 3)
GIT
remote: git://github.com/rails/turbolinks.git
- revision: 4bb563cd777875d3ad73cf007c26334f2aa8dc37
+ revision: 83d4b3d2c52a681f07900c28adb28bc8da604733
branch: master
specs:
turbolinks (3.0.0)
@@ -99,10 +99,10 @@ GIT
GIT
remote: git://github.com/sass/sass.git
- revision: 4ef8e3167985ace91b2105916756bd93c5d7bba6
+ revision: 4e3e1d5684cc29073a507578fc977434ff488c93
branch: stable
specs:
- sass (3.4.18)
+ sass (3.4.19)
PATH
remote: .
@@ -177,8 +177,23 @@ GEM
bunny (2.2.0)
amq-protocol (>= 2.0.0)
byebug (6.0.2)
- celluloid (0.16.0)
- timers (~> 4.0.0)
+ celluloid (0.17.2)
+ celluloid-essentials
+ celluloid-extras
+ celluloid-fsm
+ celluloid-pool
+ celluloid-supervision
+ timers (>= 4.1.1)
+ celluloid-essentials (0.20.5)
+ timers (>= 4.1.1)
+ celluloid-extras (0.20.5)
+ timers (>= 4.1.1)
+ celluloid-fsm (0.20.5)
+ timers (>= 4.1.1)
+ celluloid-pool (0.20.5)
+ timers (>= 4.1.1)
+ celluloid-supervision (0.20.5)
+ timers (>= 4.1.1)
coffee-rails (4.1.0)
coffee-script (>= 2.2.0)
railties (>= 4.0.0, < 5.0)
@@ -186,15 +201,15 @@ GEM
coffee-script-source
execjs
coffee-script-source (1.9.1.1)
- concurrent-ruby (1.0.0.pre3)
+ concurrent-ruby (1.0.0.pre4)
connection_pool (2.2.0)
dalli (2.7.4)
dante (0.2.0)
- delayed_job (4.0.6)
+ delayed_job (4.1.1)
activesupport (>= 3.0, < 5.0)
- delayed_job_active_record (4.0.3)
- activerecord (>= 3.0, < 5.0)
- delayed_job (>= 3.0, < 4.1)
+ delayed_job_active_record (4.1.0)
+ activerecord (>= 3.0, < 5)
+ delayed_job (>= 3.0, < 5)
erubis (2.7.0)
execjs (2.6.0)
hitimes (1.2.3)
@@ -217,18 +232,14 @@ GEM
multi_json (1.11.2)
mustache (1.0.2)
mysql (2.9.1)
- mysql2 (0.4.0)
+ mysql2 (0.4.1)
nokogiri (1.6.7.rc3)
mini_portile (~> 0.7.0.rc4)
- nokogiri (1.6.7.rc3-x64-mingw32)
- mini_portile (~> 0.7.0.rc4)
- nokogiri (1.6.7.rc3-x86-mingw32)
- mini_portile (~> 0.7.0.rc4)
pg (0.18.3)
psych (2.0.15)
que (0.11.2)
- racc (1.4.12)
- rack-cache (1.2)
+ racc (1.4.13)
+ rack-cache (1.5.0)
rack (>= 0.4)
rack-test (0.6.3)
rack (>= 1.0)
@@ -257,15 +268,15 @@ GEM
redis (~> 3.0)
resque (~> 1.25)
rufus-scheduler (~> 3.0)
- rufus-scheduler (3.1.4)
+ rufus-scheduler (3.1.7)
sdoc (0.4.1)
json (~> 1.7, >= 1.7.7)
rdoc (~> 4.0)
- sequel (4.26.0)
- serverengine (1.5.10)
+ sequel (4.27.0)
+ serverengine (1.5.11)
sigdump (~> 0.2.2)
- sidekiq (3.4.2)
- celluloid (~> 0.16.0)
+ sidekiq (3.5.1)
+ celluloid (~> 0.17.2)
connection_pool (~> 2.2, >= 2.2.0)
json (~> 1.0)
redis (~> 3.2, >= 3.2.1)
@@ -273,23 +284,23 @@ GEM
sigdump (0.2.3)
sinatra (1.0)
rack (>= 1.0)
- sneakers (2.2.0)
+ sneakers (2.3.5)
bunny (~> 2.2.0)
- serverengine (~> 1.5.5)
+ serverengine (~> 1.5.11)
thor
thread (~> 0.1.7)
- sqlite3 (1.3.10)
+ sqlite3 (1.3.11)
stackprof (0.2.7)
- sucker_punch (1.5.1)
- celluloid (= 0.16.0)
+ sucker_punch (1.6.0)
+ celluloid (~> 0.17.2)
thor (0.19.1)
thread (0.1.7)
thread_safe (0.3.5)
- timers (4.0.4)
+ timers (4.1.1)
hitimes
tzinfo (1.2.2)
thread_safe (~> 0.1)
- tzinfo-data (1.2015.6)
+ tzinfo-data (1.2015.7)
tzinfo (>= 1.0.0)
uglifier (2.7.2)
execjs (>= 0.3.0)
diff --git a/Rakefile b/Rakefile
index db27105cc3..2ec39a1c85 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,4 +1,3 @@
-require 'sdoc'
require 'net/http'
$:.unshift File.expand_path('..', __FILE__)
diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb
index 04e00cf481..6124ffeb52 100644
--- a/actionmailer/test/i18n_with_controller_test.rb
+++ b/actionmailer/test/i18n_with_controller_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
require 'action_view'
require 'action_controller'
-require 'active_support/deprecation'
class I18nTestMailer < ActionMailer::Base
configure do |c|
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index b9b771b930..4f95a9bab9 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,22 @@
+* Catch invalid UTF-8 querystring values and respond with BadRequest
+
+ Check querystring params for invalid UTF-8 characters, and raise an
+ ActionController::BadRequest error if present. Previously these strings
+ would typically trigger errors further down the stack.
+
+ *Grey Baker*
+
+* Parse RSS/ATOM responses as XML, not HTML.
+
+ *Alexander Kaupanin*
+
+* Show helpful message in `BadRequest` exceptions due to invalid path
+ parameter encodings.
+
+ Fixes #21923.
+
+ *Agis Anastasopoulos*
+
* Deprecate `config.static_cache_control` in favor of
`config.public_file_server.headers`
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 13795f0dd8..287550db42 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -61,7 +61,7 @@ module AbstractController
# impossible to skip a callback defined using an anonymous proc
# using #skip_action_callback
def skip_action_callback(*names)
- ActiveSupport::Deprecation.warn('`skip_action_callback` is deprecated and will be removed in the next major version of Rails. Please use skip_before_action, skip_after_action or skip_around_action instead.')
+ ActiveSupport::Deprecation.warn('`skip_action_callback` is deprecated and will be removed in Rails 5.1. Please use skip_before_action, skip_after_action or skip_around_action instead.')
skip_before_action(*names, raise: false)
skip_after_action(*names, raise: false)
skip_around_action(*names, raise: false)
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 94ec62ec6f..8e040bb465 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/array/extract_options'
require 'action_dispatch/middleware/stack'
-require 'active_support/deprecation'
require 'action_dispatch/http/request'
require 'action_dispatch/http/response'
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
index 18e003741d..5260dc0336 100644
--- a/actionpack/lib/action_controller/metal/exceptions.rb
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -5,12 +5,10 @@ module ActionController
class BadRequest < ActionControllerError #:nodoc:
attr_reader :original_exception
- def initialize(type = nil, e = nil)
- return super() unless type && e
-
- super("Invalid #{type} parameters: #{e.message}")
+ def initialize(msg = nil, e = nil)
+ super(msg)
@original_exception = e
- set_backtrace e.backtrace
+ set_backtrace e.backtrace if e
end
end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 58df5c539e..6e346fadfe 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -91,11 +91,11 @@ module ActionController #:nodoc:
# and accept Rails' defaults, life will be much easier.
#
# If you need to use a MIME type which isn't supported by default, you can register your own handlers in
- # config/initializers/mime_types.rb as follows.
+ # +config/initializers/mime_types.rb+ as follows.
#
# Mime::Type.register "image/jpg", :jpg
#
- # Respond to also allows you to specify a common block for different formats by using any:
+ # Respond to also allows you to specify a common block for different formats by using +any+:
#
# def index
# @people = Person.all
@@ -151,7 +151,7 @@ module ActionController #:nodoc:
# format.html.none { render "trash" }
# end
#
- # Variants also support common `any`/`all` block that formats have.
+ # Variants also support common +any+/+all+ block that formats have.
#
# It works for both inline:
#
@@ -174,7 +174,7 @@ module ActionController #:nodoc:
# request.variant = [:tablet, :phone]
#
# which will work similarly to formats and MIME types negotiation. If there will be no
- # :tablet variant declared, :phone variant will be picked:
+ # +:tablet+ variant declared, +:phone+ variant will be picked:
#
# respond_to do |format|
# format.html.none
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 172fbdf954..cce6fe7787 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -1,4 +1,3 @@
-require 'active_support/deprecation'
require 'active_support/core_ext/string/filters'
module ActionController
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 380e9d29b4..2cada1f68a 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -522,7 +522,7 @@ module ActionController
@request.delete_header 'HTTP_COOKIE'
if @request.have_cookie_jar?
- unless @response.committed?
+ unless @request.cookie_jar.committed?
@request.cookie_jar.write(@response)
self.cookies.update(@request.cookie_jar.instance_variable_get(:@cookies))
end
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index 95094c25c0..b64f660ec5 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -1,7 +1,6 @@
require 'singleton'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/string/starts_ends_with'
-require 'active_support/deprecation'
module Mime
class Mimes
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index bf20a33d36..35e3ac304f 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -65,7 +65,7 @@ module ActionDispatch
path_parameters.each do |key, value|
next unless value.respond_to?(:valid_encoding?)
unless value.valid_encoding?
- raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
+ raise ActionController::BadRequest, "Invalid parameter encoding: #{key} => #{value.inspect}"
end
end
end
@@ -338,10 +338,13 @@ module ActionDispatch
# Override Rack's GET method to support indifferent access
def GET
fetch_header("action_dispatch.request.query_parameters") do |k|
- set_header k, Request::Utils.normalize_encode_params(super || {})
+ rack_query_params = super || {}
+ # Check for non UTF-8 parameter values, which would cause errors later
+ Request::Utils.check_param_encoding(rack_query_params)
+ set_header k, Request::Utils.normalize_encode_params(rack_query_params)
end
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
- raise ActionController::BadRequest.new(:query, e)
+ raise ActionController::BadRequest.new("Invalid query parameters: #{e.message}", e)
end
alias :query_parameters :GET
@@ -357,7 +360,7 @@ module ActionDispatch
self.request_parameters = Request::Utils.normalize_encode_params(super || {})
raise
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
- raise ActionController::BadRequest.new(:request, e)
+ raise ActionController::BadRequest.new("Invalid request parameters: #{e.message}", e)
end
alias :request_parameters :POST
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index c54efb6541..f0127aa276 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -149,7 +149,6 @@ module ActionDispatch # :nodoc:
self.body, self.status = body, status
- @blank = false
@cv = new_cond
@committed = false
@sending = false
@@ -287,12 +286,8 @@ module ActionDispatch # :nodoc:
@stream.write string
end
- EMPTY = " "
-
# Allows you to manually set or override the response body.
def body=(body)
- @blank = true if body == EMPTY
-
if body.respond_to?(:to_path)
@stream = body
else
diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb
index 6c7fba00cb..af9a29eb07 100644
--- a/actionpack/lib/action_dispatch/middleware/reloader.rb
+++ b/actionpack/lib/action_dispatch/middleware/reloader.rb
@@ -1,5 +1,3 @@
-require 'active_support/deprecation/reporting'
-
module ActionDispatch
# ActionDispatch::Reloader provides prepare and cleanup callbacks,
# intended to assist with code reloading during development.
diff --git a/actionpack/lib/action_dispatch/request/utils.rb b/actionpack/lib/action_dispatch/request/utils.rb
index a8151a8224..bb3df3c311 100644
--- a/actionpack/lib/action_dispatch/request/utils.rb
+++ b/actionpack/lib/action_dispatch/request/utils.rb
@@ -13,6 +13,21 @@ module ActionDispatch
end
end
+ def self.check_param_encoding(params)
+ case params
+ when Array
+ params.each { |element| check_param_encoding(element) }
+ when Hash
+ params.each_value { |value| check_param_encoding(value) }
+ when String
+ unless params.valid_encoding?
+ # Raise Rack::Utils::InvalidParameterError for consistency with Rack.
+ # ActionDispatch::Request#GET will re-raise as a BadRequest error.
+ raise Rack::Utils::InvalidParameterError, "Non UTF-8 value: #{params}"
+ end
+ end
+ end
+
class ParamEncoder # :nodoc:
# Convert nested Hash to HashWithIndifferentAccess.
#
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 921cda91ee..7c0404ca62 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -3,7 +3,6 @@ require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/regexp'
-require 'active_support/deprecation'
require 'action_dispatch/routing/redirection'
require 'action_dispatch/routing/endpoint'
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 339e2b7c4a..5f54ea130b 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -1,5 +1,4 @@
require 'action_dispatch/journey'
-require 'forwardable'
require 'active_support/concern'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb
index 8dd0bd63ad..fae266273e 100644
--- a/actionpack/lib/action_dispatch/testing/assertions.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions.rb
@@ -12,7 +12,7 @@ module ActionDispatch
include Rails::Dom::Testing::Assertions
def html_document
- @html_document ||= if @response.content_type === Mime[:xml]
+ @html_document ||= if @response.content_type.to_s =~ /xml\z/
Nokogiri::XML::Document.parse(@response.body)
else
Nokogiri::HTML::Document.parse(@response.body)
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 7e59bb68cf..790f9ea5d2 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -131,35 +131,35 @@ module ActionDispatch
# Performs a GET request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def get_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`get_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`get_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:get, path, *args)
end
# Performs a POST request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def post_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`post_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`post_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:post, path, *args)
end
# Performs a PATCH request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def patch_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`patch_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`patch_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:patch, path, *args)
end
# Performs a PUT request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def put_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`put_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`put_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:put, path, *args)
end
# Performs a DELETE request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def delete_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`delete_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`delete_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:delete, path, *args)
end
end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index de7e800ac1..d0a1d1285f 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -402,6 +402,8 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
format.html { render plain: "OK", status: 200 }
format.js { render plain: "JS OK", status: 200 }
format.xml { render :xml => "<root></root>", :status => 200 }
+ format.rss { render :xml => "<root></root>", :status => 200 }
+ format.atom { render :xml => "<root></root>", :status => 200 }
end
end
@@ -458,19 +460,21 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
end
end
- def test_get_xml
- with_test_route_set do
- get "/get", params: {}, headers: {"HTTP_ACCEPT" => "application/xml"}
- assert_equal 200, status
- assert_equal "OK", status_message
- assert_response 200
- assert_response :success
- assert_response :ok
- assert_equal({}, cookies.to_hash)
- assert_equal "<root></root>", body
- assert_equal "<root></root>", response.body
- assert_instance_of Nokogiri::XML::Document, html_document
- assert_equal 1, request_count
+ def test_get_xml_rss_atom
+ %w[ application/xml application/rss+xml application/atom+xml ].each do |mime_string|
+ with_test_route_set do
+ get "/get", headers: {"HTTP_ACCEPT" => mime_string}
+ assert_equal 200, status
+ assert_equal "OK", status_message
+ assert_response 200
+ assert_response :success
+ assert_response :ok
+ assert_equal({}, cookies.to_hash)
+ assert_equal "<root></root>", body
+ assert_equal "<root></root>", response.body
+ assert_instance_of Nokogiri::XML::Document, html_document
+ assert_equal 1, request_count
+ end
end
end
diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb
index 4d1c23cbee..4224ac2a1b 100644
--- a/actionpack/test/controller/live_stream_test.rb
+++ b/actionpack/test/controller/live_stream_test.rb
@@ -388,8 +388,14 @@ module ActionController
end
def test_exception_callback_when_committed
+ current_threads = Thread.list
+
capture_log_output do |output|
get :exception_with_callback, format: 'text/event-stream'
+
+ # Wait on the execution of all threads
+ (Thread.list - current_threads).each(&:join)
+
assert_equal %(data: "500 Internal Server Error"\n\n), response.body
assert_match 'An exception occurred...', output.rewind && output.read
assert_stream_closed
diff --git a/actionpack/test/controller/new_base/render_text_test.rb b/actionpack/test/controller/new_base/render_text_test.rb
index 435bb18dce..048458178c 100644
--- a/actionpack/test/controller/new_base/render_text_test.rb
+++ b/actionpack/test/controller/new_base/render_text_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'active_support/deprecation'
module RenderText
class MinimalController < ActionController::Metal
diff --git a/actionpack/test/controller/parameters/mutators_test.rb b/actionpack/test/controller/parameters/mutators_test.rb
index 6c57c4caeb..744d8664be 100644
--- a/actionpack/test/controller/parameters/mutators_test.rb
+++ b/actionpack/test/controller/parameters/mutators_test.rb
@@ -62,15 +62,11 @@ class ParametersMutatorsTest < ActiveSupport::TestCase
end
test "select! retains permitted status" do
- jruby_skip "https://github.com/jruby/jruby/issues/3137"
-
@params.permit!
assert @params.select! { |k| k != "person" }.permitted?
end
test "select! retains unpermitted status" do
- jruby_skip "https://github.com/jruby/jruby/issues/3137"
-
assert_not @params.select! { |k| k != "person" }.permitted?
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 82c7ebf568..256ebf6a07 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -629,13 +629,13 @@ class HttpCacheForeverTest < ActionController::TestCase
def test_cache_with_public
get :cache_me_forever, params: {public: true}
- assert_equal "max-age=#{100.years.to_i}, public", @response.headers["Cache-Control"]
+ assert_equal "max-age=#{100.years}, public", @response.headers["Cache-Control"]
assert_not_nil @response.etag
end
def test_cache_with_private
get :cache_me_forever
- assert_equal "max-age=#{100.years.to_i}, private", @response.headers["Cache-Control"]
+ assert_equal "max-age=#{100.years}, private", @response.headers["Cache-Control"]
assert_not_nil @response.etag
assert_response :success
end
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index 40c97abd35..f1a296682d 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -139,7 +139,7 @@ XML
def delete_cookie
cookies.delete("foo")
- head :ok
+ render plain: 'ok'
end
def test_without_body
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index af2ed24f43..e9896a71f4 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -961,15 +961,33 @@ class RequestParameters < BaseRequestTest
end
end
+ test "path parameters with invalid UTF8 encoding" do
+ request = stub_request(
+ "action_dispatch.request.path_parameters" => { foo: "\xBE" }
+ )
+
+ err = assert_raises(ActionController::BadRequest) do
+ request.check_path_parameters!
+ end
+
+ assert_match "Invalid parameter encoding", err.message
+ assert_match "foo", err.message
+ assert_match "\\xBE", err.message
+ end
+
test "parameters not accessible after rack parse error of invalid UTF8 character" do
request = stub_request("QUERY_STRING" => "foo%81E=1")
+ assert_raises(ActionController::BadRequest) { request.parameters }
+ end
- 2.times do
- assert_raises(ActionController::BadRequest) do
- # rack will raise a Rack::Utils::InvalidParameterError when parsing this query string
- request.parameters
- end
- end
+ test "parameters containing an invalid UTF8 character" do
+ request = stub_request("QUERY_STRING" => "foo=%81E")
+ assert_raises(ActionController::BadRequest) { request.parameters }
+ end
+
+ test "parameters containing a deeply nested invalid UTF8 character" do
+ request = stub_request("QUERY_STRING" => "foo[bar]=%81E")
+ assert_raises(ActionController::BadRequest) { request.parameters }
end
test "parameters not accessible after rack parse error 1" do
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 126379a23c..981d820ccf 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -206,8 +206,6 @@ class ResponseTest < ActiveSupport::TestCase
end
test "read content type with charset utf-16" do
- jruby_skip "https://github.com/jruby/jruby/issues/3138"
-
original = ActionDispatch::Response.default_charset
begin
ActionDispatch::Response.default_charset = 'utf-16'
diff --git a/actionpack/test/dispatch/routing/concerns_test.rb b/actionpack/test/dispatch/routing/concerns_test.rb
index 361ceca677..7ef513b0c8 100644
--- a/actionpack/test/dispatch/routing/concerns_test.rb
+++ b/actionpack/test/dispatch/routing/concerns_test.rb
@@ -109,8 +109,6 @@ class RoutingConcernsTest < ActionDispatch::IntegrationTest
end
def test_concerns_executes_block_in_context_of_current_mapper
- jruby_skip "https://github.com/jruby/jruby/issues/3143"
-
mapper = ActionDispatch::Routing::Mapper.new(ActionDispatch::Routing::RouteSet.new)
mapper.concern :test_concern do
resources :things
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index cbb12a2209..15dd702161 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -93,13 +93,13 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_kind_of AbstractController::ActionNotFound, env["action_dispatch.exception"]
assert_equal "/404", env["PATH_INFO"]
assert_equal "/not_found_original_exception", env["action_dispatch.original_path"]
- [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED"]]
end
@app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
get "/not_found_original_exception", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
- assert_equal "YOU FAILED BRO", body
+ assert_equal "YOU FAILED", body
end
test "returns an empty response if custom exceptions app returns X-Cascade pass" do
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index e62ed09b0a..1da57ab50b 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -75,8 +75,6 @@ module StaticTests
end
def test_served_static_file_with_non_english_filename
- jruby_skip "Stop skipping if following bug gets fixed: " \
- "http://jira.codehaus.org/browse/JRUBY-7192"
assert_html "means hello in Japanese\n", get("/foo/#{Rack::Utils.escape("こんにちは.html")}")
end
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index b27c0a29c6..c010b7ce91 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,3 +1,8 @@
+* Collection input propagates input's `id` to the label's `for` attribute when
+ using html options as the last element of collection.
+
+ *Vasiliy Ermolovich*
+
* Add a `hidden_field` on the `collection_radio_buttons` to avoid raising a error
when the only input on the form is the `collection_radio_buttons`.
diff --git a/actionview/lib/action_view/helpers/tags/collection_helpers.rb b/actionview/lib/action_view/helpers/tags/collection_helpers.rb
index fea4c8d4ec..b87b4281d6 100644
--- a/actionview/lib/action_view/helpers/tags/collection_helpers.rb
+++ b/actionview/lib/action_view/helpers/tags/collection_helpers.rb
@@ -19,6 +19,8 @@ module ActionView
def label(label_html_options={}, &block)
html_options = @input_html_options.slice(:index, :namespace).merge(label_html_options)
+ html_options[:for] ||= @input_html_options[:id] if @input_html_options[:id]
+
@template_object.label(@object_name, @sanitized_attribute_name, @text, html_options, &block)
end
end
diff --git a/actionview/test/actionpack/abstract/render_test.rb b/actionview/test/actionpack/abstract/render_test.rb
index e5721d6416..e185b76adb 100644
--- a/actionview/test/actionpack/abstract/render_test.rb
+++ b/actionview/test/actionpack/abstract/render_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'active_support/deprecation'
module AbstractController
module Testing
diff --git a/actionview/test/fixtures/digestor/comments/_comment.html.erb b/actionview/test/fixtures/digestor/comments/_comment.html.erb
index f172e749da..a8fa21f644 100644
--- a/actionview/test/fixtures/digestor/comments/_comment.html.erb
+++ b/actionview/test/fixtures/digestor/comments/_comment.html.erb
@@ -1 +1 @@
-Great story, bro!
+Great story!
diff --git a/actionview/test/template/form_collections_helper_test.rb b/actionview/test/template/form_collections_helper_test.rb
index 41932d15ee..b59be8e36c 100644
--- a/actionview/test/template/form_collections_helper_test.rb
+++ b/actionview/test/template/form_collections_helper_test.rb
@@ -306,6 +306,17 @@ class FormCollectionsHelperTest < ActionView::TestCase
assert_select 'input[type=checkbox][value="2"].bar'
end
+ test 'collection check boxes propagates input id to the label for attribute' do
+ collection = [[1, 'Category 1', {id: 'foo'}], [2, 'Category 2', {id: 'bar'}]]
+ with_collection_check_boxes :user, :active, collection, :first, :second
+
+ assert_select 'input[type=checkbox][value="1"]#foo'
+ assert_select 'input[type=checkbox][value="2"]#bar'
+
+ assert_select 'label[for=foo]'
+ assert_select 'label[for=bar]'
+ end
+
test 'collection check boxes sets the label class defined inside the block' do
collection = [[1, 'Category 1', {class: 'foo'}], [2, 'Category 2', {class: 'bar'}]]
with_collection_check_boxes :user, :active, collection, :second, :first do |b|
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 4ba4e3e8f7..9c1e8b4ba7 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -20,7 +20,7 @@ module ActiveModel
def validate_each(record, attr_name, value)
before_type_cast = :"#{attr_name}_before_type_cast"
- raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast)
+ raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast) && record.send(before_type_cast) != value
raw_value ||= value
if record_attribute_changed_in_place?(record, attr_name)
@@ -29,16 +29,14 @@ module ActiveModel
return if options[:allow_nil] && raw_value.nil?
- unless value = parse_raw_value_as_a_number(raw_value)
+ unless is_number?(raw_value)
record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
return
end
- if allow_only_integer?(record)
- unless value = parse_raw_value_as_an_integer(raw_value)
- record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
- return
- end
+ if allow_only_integer?(record) && !is_integer?(raw_value)
+ record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
+ return
end
options.slice(*CHECKS.keys).each do |option, option_value|
@@ -64,14 +62,15 @@ module ActiveModel
protected
- def parse_raw_value_as_a_number(raw_value)
- Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
+ def is_number?(raw_value)
+ parsed_value = Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
+ !parsed_value.nil?
rescue ArgumentError, TypeError
- nil
+ false
end
- def parse_raw_value_as_an_integer(raw_value)
- raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\z/
+ def is_integer?(raw_value)
+ /\A[+-]?\d+\z/ === raw_value.to_s
end
def filtered_options(value)
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index 05432abaff..04ec74bad3 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -4,6 +4,7 @@ require 'models/topic'
require 'models/person'
require 'bigdecimal'
+require 'active_support/core_ext/big_decimal'
class NumericalityValidationTest < ActiveModel::TestCase
@@ -71,6 +72,13 @@ class NumericalityValidationTest < ActiveModel::TestCase
valid!([11])
end
+ def test_validates_numericality_with_greater_than_using_differing_numeric_types
+ Topic.validates_numericality_of :approved, greater_than: BigDecimal.new('97.18')
+
+ invalid!([-97.18, BigDecimal.new('97.18'), BigDecimal('-97.18')], 'must be greater than 97.18')
+ valid!([97.18, 98, BigDecimal.new('98')]) # Notice the 97.18 as a float is greater than 97.18 as a BigDecimal due to floating point precision
+ end
+
def test_validates_numericality_with_greater_than_or_equal
Topic.validates_numericality_of :approved, greater_than_or_equal_to: 10
@@ -78,6 +86,13 @@ class NumericalityValidationTest < ActiveModel::TestCase
valid!([10])
end
+ def test_validates_numericality_with_greater_than_or_equal_using_differing_numeric_types
+ Topic.validates_numericality_of :approved, greater_than_or_equal_to: BigDecimal.new('97.18')
+
+ invalid!([-97.18, 97.17, 97, BigDecimal.new('97.17'), BigDecimal.new('-97.18')], 'must be greater than or equal to 97.18')
+ valid!([97.18, 98, BigDecimal.new('97.19')])
+ end
+
def test_validates_numericality_with_equal_to
Topic.validates_numericality_of :approved, equal_to: 10
@@ -85,6 +100,13 @@ class NumericalityValidationTest < ActiveModel::TestCase
valid!([10])
end
+ def test_validates_numericality_with_equal_to_using_differing_numeric_types
+ Topic.validates_numericality_of :approved, equal_to: BigDecimal.new('97.18')
+
+ invalid!([-97.18, 97.18], 'must be equal to 97.18')
+ valid!([BigDecimal.new('97.18')])
+ end
+
def test_validates_numericality_with_less_than
Topic.validates_numericality_of :approved, less_than: 10
@@ -92,6 +114,13 @@ class NumericalityValidationTest < ActiveModel::TestCase
valid!([-9, 9])
end
+ def test_validates_numericality_with_less_than_using_differing_numeric_types
+ Topic.validates_numericality_of :approved, less_than: BigDecimal.new('97.18')
+
+ invalid!([97.18, BigDecimal.new('97.18')], 'must be less than 97.18')
+ valid!([-97.0, 97.0, -97, 97, BigDecimal.new('-97'), BigDecimal.new('97')])
+ end
+
def test_validates_numericality_with_less_than_or_equal_to
Topic.validates_numericality_of :approved, less_than_or_equal_to: 10
@@ -99,6 +128,13 @@ class NumericalityValidationTest < ActiveModel::TestCase
valid!([-10, 10])
end
+ def test_validates_numericality_with_less_than_or_equal_to_using_differing_numeric_types
+ Topic.validates_numericality_of :approved, less_than_or_equal_to: BigDecimal.new('97.18')
+
+ invalid!([97.18, 98], 'must be less than or equal to 97.18')
+ valid!([-97.18, BigDecimal.new('-97.18'), BigDecimal.new('97.18')])
+ end
+
def test_validates_numericality_with_odd
Topic.validates_numericality_of :approved, odd: true
@@ -196,7 +232,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def valid!(values)
with_each_topic_approved_value(values) do |topic, value|
- assert topic.valid?, "#{value.inspect} not accepted as a number"
+ assert topic.valid?, "#{value.inspect} not accepted as a number with validation error: #{topic.errors[:approved].first}"
end
end
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 9e44131fa9..86738fa819 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,107 @@
+* Add support for bidirectional destroy dependencies.
+
+ Fixes #13609.
+
+ Example:
+
+ class Content < ActiveRecord::Base
+ has_one :position, dependent: :destroy
+ end
+
+ class Position < ActiveRecord::Base
+ belongs_to :content, dependent: :destroy
+ end
+
+ *Seb Jacobs*
+
+* Includes HABTM returns correct size now. It's caused by the join dependency
+ only instantiates one HABTM object because the join table hasn't a primary key.
+
+ Fixes #16032.
+
+ Examples:
+
+ before:
+
+ Project.first.salaried_developers.size # => 3
+ Project.includes(:salaried_developers).first.salaried_developers.size # => 1
+
+ after:
+
+ Project.first.salaried_developers.size # => 3
+ Project.includes(:salaried_developers).first.salaried_developers.size # => 3
+
+ *Bigxiang*
+
+* Add option to index errors in nested attributes
+
+ For models which have nested attributes, errors within those models will
+ now be indexed if :index_errors is specified when defining a
+ has_many relationship, or if its set in the global config.
+
+ Example:
+
+ class Guitar < ActiveRecord::Base
+ has_many :tuning_pegs
+ accepts_nested_attributes_for :tuning_pegs
+ end
+
+ class TuningPeg < ActiveRecord::Base
+ belongs_to :guitar
+ validates_numericality_of :pitch
+ end
+
+ - Old style
+ - `guitar.errors["tuning_pegs.pitch"] = ["is not a number"]`
+
+ - New style (if defined globally, or set in has_many_relationship)
+ - `guitar.errors["tuning_pegs[1].pitch"] = ["is not a number"]`
+
+ *Michael Probber and Terence Sun*
+
+* Exit with non-zero status for failed database rake tasks.
+
+ *Jay Hayes*
+
+* Queries such as `Computer.joins(:monitor).group(:status).count` will now be
+ interpreted as `Computer.joins(:monitor).group('computers.status').count`
+ so that when `Computer` and `Monitor` have both `status` columns we don't
+ have conflicts in projection.
+
+ *Rafael Sales*
+
+* Add ability to default to `uuid` as primary key when generating database migrations
+
+ config.generators do |g|
+ g.orm :active_record, primary_key_type: :uuid
+ end
+
+ *Jon McCartie*
+
+* Don't cache arguments in #find_by if they are an ActiveRecord::Relation
+
+ Fixes #20817
+
+ *Hiroaki Izu*
+
+* Qualify column name inserted by `group` in calculation
+
+ Giving `group` an unqualified column name now works, even if the relation
+ has `JOIN` with another table which also has a column of the name.
+
+ *Soutaro Matsumoto*
+
+* Don't cache prepared statements containing an IN clause or a SQL literal, as
+ these queries will change often and are unlikely to have a cache hit.
+
+ *Sean Griffin*
+
+* Fix `rewhere` in a `has_many` association.
+
+ Fixes #21955.
+
+ *Josh Branchaud*, *Kal*
+
* `where` raises ArgumentError on unsupported types.
Fixes #20473.
@@ -71,9 +175,8 @@
database.
- m = Model.create!
- m.created_at.usec == m.reload.created_at.usec
- # => false
+ m = Model.create!
+ m.created_at.usec == m.reload.created_at.usec # => false
# due to different precision in Time.now and database column
If the precision is low enough, (mysql default is 0, so it is always low
@@ -261,9 +364,9 @@
Example:
- @users = User.where("name like ?", "%Alberto%")
- @users.cache_key
- => "/users/query-5942b155a43b139f2471b872ac54251f-3-20150714212107656125000"
+ @users = User.where("name like ?", "%Alberto%")
+ @users.cache_key
+ # => "/users/query-5942b155a43b139f2471b872ac54251f-3-20150714212107656125000"
*Alberto Fernández-Capel*
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 2abc5fa9d5..b806a2f832 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -149,7 +149,7 @@ module ActiveRecord
class HasOneThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc:
end
- # This error is raised when trying to eager load a poloymorphic association using a JOIN.
+ # This error is raised when trying to eager load a polymorphic association using a JOIN.
# Eager loading polymorphic associations is only possible with
# {ActiveRecord::Relation#preload}[rdoc-ref:QueryMethods#preload].
class EagerLoadPolymorphicError < ActiveRecordError
@@ -508,7 +508,7 @@ module ActiveRecord
# to customize them. For example, to add a condition:
#
# class Blog < ActiveRecord::Base
- # has_many :published_posts, -> { where published: true }, class_name: 'Post'
+ # has_many :published_posts, -> { where(published: true) }, class_name: 'Post'
# end
#
# Inside the <tt>-> { ... }</tt> block you can use all of the usual Relation methods.
@@ -520,7 +520,7 @@ module ActiveRecord
# events that occur on the user's birthday:
#
# class User < ActiveRecord::Base
- # has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
+ # has_many :birthday_events, ->(user) { where(starts_on: user.birthday) }, class_name: 'Event'
# end
#
# Note: Joining, eager loading and preloading of these associations is not fully possible.
@@ -895,7 +895,7 @@ module ActiveRecord
# In this case it is usually more natural to include an association which has conditions defined on it:
#
# class Post < ActiveRecord::Base
- # has_many :approved_comments, -> { where approved: true }, class_name: 'Comment'
+ # has_many :approved_comments, -> { where(approved: true) }, class_name: 'Comment'
# end
#
# Post.includes(:approved_comments)
@@ -1345,10 +1345,10 @@ module ActiveRecord
# association objects.
#
# Option examples:
- # has_many :comments, -> { order "posted_on" }
- # has_many :comments, -> { includes :author }
+ # has_many :comments, -> { order("posted_on") }
+ # has_many :comments, -> { includes(:author) }
# has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person"
- # has_many :tracks, -> { order "position" }, dependent: :destroy
+ # has_many :tracks, -> { order("position") }, dependent: :destroy
# has_many :comments, dependent: :nullify
# has_many :tags, as: :taggable
# has_many :reports, -> { readonly }
@@ -1476,12 +1476,12 @@ module ActiveRecord
# has_one :credit_card, dependent: :destroy # destroys the associated credit card
# has_one :credit_card, dependent: :nullify # updates the associated records foreign
# # key value to NULL rather than destroying it
- # has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment"
- # has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person"
+ # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment"
+ # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person"
# has_one :attachment, as: :attachable
# has_one :boss, -> { readonly }
# has_one :club, through: :membership
- # has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
+ # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable
# has_one :credit_card, required: true
def has_one(name, scope = nil, options = {})
reflection = Builder::HasOne.build(self, name, scope, options)
@@ -1721,7 +1721,7 @@ module ActiveRecord
# query when you access the associated collection.
#
# Scope examples:
- # has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
+ # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
# has_and_belongs_to_many :categories, ->(category) {
# where("default_category = ?", category.name)
# }
@@ -1774,7 +1774,7 @@ module ActiveRecord
#
# Option examples:
# has_and_belongs_to_many :projects
- # has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
+ # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
# has_and_belongs_to_many :nations, class_name: "Country"
# has_and_belongs_to_many :categories, join_table: "prods_cats"
# has_and_belongs_to_many :categories, -> { readonly }
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index a140dc239c..48437a1c9e 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -147,9 +147,9 @@ module ActiveRecord
scope.includes! item.includes_values
end
+ scope.unscope!(*item.unscope_values)
scope.where_clause += item.where_clause
scope.order_values |= item.order_values
- scope.unscope!(*item.unscope_values)
end
reflection = reflection.next
diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb
index f71b10120f..7864d4c536 100644
--- a/activerecord/lib/active_record/associations/builder/has_many.rb
+++ b/activerecord/lib/active_record/associations/builder/has_many.rb
@@ -5,7 +5,7 @@ module ActiveRecord::Associations::Builder # :nodoc:
end
def self.valid_options(options)
- super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type]
+ super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors]
end
def self.valid_dependent_options
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 256df3ca11..f32dddb8f0 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -1,5 +1,3 @@
-require "active_support/deprecation"
-
module ActiveRecord
module Associations
# = Active Record Association Collection
diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb
index 81eb5136a1..0e98a3b3a4 100644
--- a/activerecord/lib/active_record/associations/join_dependency.rb
+++ b/activerecord/lib/active_record/associations/join_dependency.rb
@@ -131,9 +131,9 @@ module ActiveRecord
def instantiate(result_set, aliases)
primary_key = aliases.column_alias(join_root, join_root.primary_key)
- seen = Hash.new { |h,parent_klass|
- h[parent_klass] = Hash.new { |i,parent_id|
- i[parent_id] = Hash.new { |j,child_klass| j[child_klass] = {} }
+ seen = Hash.new { |i, object_id|
+ i[object_id] = Hash.new { |j, child_class|
+ j[child_class] = {}
}
}
@@ -150,7 +150,8 @@ module ActiveRecord
message_bus.instrument('instantiation.active_record', payload) do
result_set.each { |row_hash|
- parent = parents[row_hash[primary_key]] ||= join_root.instantiate(row_hash, column_aliases)
+ parent_key = primary_key ? row_hash[primary_key] : row_hash
+ parent = parents[parent_key] ||= join_root.instantiate(row_hash, column_aliases)
construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases)
}
end
@@ -233,7 +234,6 @@ module ActiveRecord
def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
return if ar_parent.nil?
- primary_id = ar_parent.id
parent.children.each do |node|
if node.reflection.collection?
@@ -253,14 +253,14 @@ module ActiveRecord
next
end
- model = seen[parent.base_klass][primary_id][node.base_klass][id]
+ model = seen[ar_parent.object_id][node.base_klass][id]
if model
construct(model, node, row, rs, seen, model_cache, aliases)
else
model = construct_model(ar_parent, node, row, model_cache, id, aliases)
model.readonly!
- seen[parent.base_klass][primary_id][node.base_klass][id] = model
+ seen[ar_parent.object_id][node.base_klass][id] = model
construct(model, node, row, rs, seen, model_cache, aliases)
end
end
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
index 3992a240b9..ecf6fb8643 100644
--- a/activerecord/lib/active_record/associations/preloader.rb
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -54,6 +54,8 @@ module ActiveRecord
autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
end
+ NULL_RELATION = Struct.new(:values, :where_clause, :joins_values).new({}, Relation::WhereClause.empty, [])
+
# Eager loads the named associations for the given Active Record record(s).
#
# In this description, 'association name' shall refer to the name passed
@@ -88,9 +90,6 @@ module ActiveRecord
# [ :books, :author ]
# { author: :avatar }
# [ :books, { author: :avatar } ]
-
- NULL_RELATION = Struct.new(:values, :where_clause, :joins_values).new({}, Relation::WhereClause.empty, [])
-
def preload(records, associations, preload_scope = nil)
records = Array.wrap(records).compact.uniq
associations = Array.wrap(associations)
@@ -107,6 +106,7 @@ module ActiveRecord
private
+ # Loads all the given data into +records+ for the +association+.
def preloaders_on(association, records, scope)
case association
when Hash
@@ -132,6 +132,11 @@ module ActiveRecord
}
end
+ # Loads all the given data into +records+ for a singular +association+.
+ #
+ # Functions by instantiating a preloader class such as Preloader::HasManyThrough and
+ # call the +run+ method for each passed in class in the +records+ argument.
+ #
# Not all records have the same class, so group then preload group on the reflection
# itself so that if various subclass share the same association then we do not split
# them unnecessarily
@@ -181,6 +186,10 @@ module ActiveRecord
def self.preloaded_records; []; end
end
+ # Returns a class containing the logic needed to load preload the data
+ # and attach it to a relation. For example +Preloader::Association+ or
+ # +Preloader::HasManyThrough+. The class returned implements a `run` method
+ # that accepts a preloader.
def preloader_for(reflection, owners, rhs_klass)
return NullPreloader unless rhs_klass
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index 7a5a8f8ae6..29dd0643d6 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -12,7 +12,6 @@ module ActiveRecord
@preload_scope = preload_scope
@model = owners.first && owners.first.class
@scope = nil
- @owners_by_key = nil
@preloaded_records = []
end
@@ -56,18 +55,6 @@ module ActiveRecord
raise NotImplementedError
end
- def owners_by_key
- @owners_by_key ||= if key_conversion_required?
- owners.group_by do |owner|
- owner[owner_key_name].to_s
- end
- else
- owners.group_by do |owner|
- owner[owner_key_name]
- end
- end
- end
-
def options
reflection.options
end
@@ -75,32 +62,33 @@ module ActiveRecord
private
def associated_records_by_owner(preloader)
- owners_map = owners_by_key
- owner_keys = owners_map.keys.compact
-
- # Each record may have multiple owners, and vice-versa
- records_by_owner = owners.each_with_object({}) do |owner,h|
- h[owner] = []
+ records = load_records
+ owners.each_with_object({}) do |owner, result|
+ result[owner] = records[convert_key(owner[owner_key_name])] || []
end
+ end
- if owner_keys.any?
- # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
- # Make several smaller queries if necessary or make one query if the adapter supports it
- sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size)
-
- records = load_slices sliced
- records.each do |record, owner_key|
- owners_map[owner_key].each do |owner|
- records_by_owner[owner] << record
- end
+ def owner_keys
+ unless defined?(@owner_keys)
+ @owner_keys = owners.map do |owner|
+ owner[owner_key_name]
end
+ @owner_keys.uniq!
+ @owner_keys.compact!
end
-
- records_by_owner
+ @owner_keys
end
def key_conversion_required?
- association_key_type != owner_key_type
+ @key_conversion_required ||= association_key_type != owner_key_type
+ end
+
+ def convert_key(key)
+ if key_conversion_required?
+ key.to_s
+ else
+ key
+ end
end
def association_key_type
@@ -111,17 +99,17 @@ module ActiveRecord
@model.type_for_attribute(owner_key_name.to_s).type
end
- def load_slices(slices)
- @preloaded_records = slices.flat_map { |slice|
+ def load_records
+ return {} if owner_keys.empty?
+ # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
+ # Make several smaller queries if necessary or make one query if the adapter supports it
+ slices = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size)
+ @preloaded_records = slices.flat_map do |slice|
records_for(slice)
- }
-
- @preloaded_records.map { |record|
- key = record[association_key_name]
- key = key.to_s if key_conversion_required?
-
- [record, key]
- }
+ end
+ @preloaded_records.group_by do |record|
+ convert_key(record[association_key_name])
+ end
end
def reflection_scope
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
index 03cb8cb8c3..c7cc48ba16 100644
--- a/activerecord/lib/active_record/associations/singular_association.rb
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -1,5 +1,3 @@
-require "active_support/deprecation"
-
module ActiveRecord
module Associations
class SingularAssociation < Association #:nodoc:
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index d35bc3e794..fc12c3f45a 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -140,6 +140,8 @@ module ActiveRecord
included do
Associations::Builder::Association.extensions << AssociationBuilderExtension
+ mattr_accessor :index_nested_attribute_errors, instance_writer: false
+ self.index_nested_attribute_errors = false
end
module ClassMethods # :nodoc:
@@ -315,7 +317,7 @@ module ActiveRecord
def validate_collection_association(reflection)
if association = association_instance_get(reflection.name)
if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
- records.each { |record| association_valid?(reflection, record) }
+ records.each_with_index { |record, index| association_valid?(reflection, record, index) }
end
end
end
@@ -323,14 +325,18 @@ module ActiveRecord
# Returns whether or not the association is valid and applies any errors to
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
# enabled records if they're marked_for_destruction? or destroyed.
- def association_valid?(reflection, record)
+ def association_valid?(reflection, record, index=nil)
return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?)
validation_context = self.validation_context unless [:create, :update].include?(self.validation_context)
unless valid = record.valid?(validation_context)
if reflection.options[:autosave]
record.errors.each do |attribute, message|
- attribute = "#{reflection.name}.#{attribute}"
+ if index.nil? || (!reflection.options[:index_errors] && !ActiveRecord::Base.index_nested_attribute_errors)
+ attribute = "#{reflection.name}.#{attribute}"
+ else
+ attribute = "#{reflection.name}[#{index}].#{attribute}"
+ end
errors[attribute] << message
errors[attribute].uniq!
end
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index bfedc4af3f..cfd8cbda67 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -292,10 +292,15 @@ module ActiveRecord
end
def destroy #:nodoc:
+ @_destroy_callback_already_called ||= false
+ return if @_destroy_callback_already_called
+ @_destroy_callback_already_called = true
_run_destroy_callbacks { super }
rescue RecordNotDestroyed => e
@_association_destroy_exception = e
false
+ ensure
+ @_destroy_callback_already_called = false
end
def touch(*) #:nodoc:
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index dbacf56795..848aeb821c 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -29,7 +29,17 @@ module ActiveRecord
# Returns an ActiveRecord::Result instance.
def select_all(arel, name = nil, binds = [])
arel, binds = binds_from_relation arel, binds
- select(to_sql(arel, binds), name, binds)
+ sql = to_sql(arel, binds)
+ if arel.is_a?(String)
+ preparable = false
+ else
+ preparable = visitor.preparable
+ end
+ if prepared_statements && preparable
+ select_prepared(sql, name, binds)
+ else
+ select(sql, name, binds)
+ end
end
# Returns a record hash with the column names as keys and column values
@@ -67,7 +77,7 @@ module ActiveRecord
# Executes +sql+ statement in the context of this connection using
# +binds+ as the bind substitutes. +name+ is logged along with
# the executed +sql+ statement.
- def exec_query(sql, name = 'SQL', binds = [])
+ def exec_query(sql, name = 'SQL', binds = [], prepare: false)
end
# Executes insert +sql+ statement in the context of this connection using
@@ -358,9 +368,12 @@ module ActiveRecord
# Returns an ActiveRecord::Result instance.
def select(sql, name = nil, binds = [])
- exec_query(sql, name, binds)
+ exec_query(sql, name, binds, prepare: false)
end
+ def select_prepared(sql, name = nil, binds = [])
+ exec_query(sql, name, binds, prepare: true)
+ end
# Returns the last auto-generated ID from the affected table.
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index bceda5abd9..e2ef56798b 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -210,7 +210,7 @@ module ActiveRecord
# An array of ColumnDefinition objects, representing the column changes
# that have been defined.
attr_accessor :indexes
- attr_reader :name, :temporary, :options, :as, :foreign_keys
+ attr_reader :name, :temporary, :options, :as, :foreign_keys, :native
def initialize(types, name, temporary, options, as = nil)
@columns_hash = {}
@@ -238,86 +238,19 @@ module ActiveRecord
end
# Instantiates a new column for the table.
- # The +type+ parameter is normally one of the migrations native types,
- # which is one of the following:
- # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
- # <tt>:integer</tt>, <tt>:bigint</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
- # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>,
- # <tt>:binary</tt>, <tt>:boolean</tt>.
- #
- # You may use a type not in this list as long as it is supported by your
- # database (for example, "polygon" in MySQL), but this will not be database
- # agnostic and should usually be avoided.
- #
- # Available options are (none of these exists by default):
- # * <tt>:limit</tt> -
- # Requests a maximum column length. This is number of characters for a <tt>:string</tt> column
- # and number of bytes for <tt>:text</tt>, <tt>:binary</tt> and <tt>:integer</tt> columns.
- # * <tt>:default</tt> -
- # The column's default value. Use nil for NULL.
- # * <tt>:null</tt> -
- # Allows or disallows +NULL+ values in the column. This option could
- # have been named <tt>:null_allowed</tt>.
- # * <tt>:precision</tt> -
- # Specifies the precision for a <tt>:decimal</tt> column.
- # * <tt>:scale</tt> -
- # Specifies the scale for a <tt>:decimal</tt> column.
+ # See {connection.add_column}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_column]
+ # for available options.
+ #
+ # Additional options are:
# * <tt>:index</tt> -
# Create an index for the column. Can be either <tt>true</tt> or an options hash.
#
- # Note: The precision is the total number of significant digits
- # and the scale is the number of digits that can be stored following
- # the decimal point. For example, the number 123.45 has a precision of 5
- # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
- # range from -999.99 to 999.99.
- #
- # Please be aware of different RDBMS implementations behavior with
- # <tt>:decimal</tt> columns:
- # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
- # <tt>:precision</tt>, and makes no comments about the requirements of
- # <tt>:precision</tt>.
- # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
- # Default is (10,0).
- # * PostgreSQL: <tt>:precision</tt> [1..infinity],
- # <tt>:scale</tt> [0..infinity]. No default.
- # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
- # Internal storage as strings. No default.
- # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
- # but the maximum supported <tt>:precision</tt> is 16. No default.
- # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
- # Default is (38,0).
- # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
- # Default unknown.
- # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
- # Default (38,0).
- #
# This method returns <tt>self</tt>.
#
# == Examples
- # # Assuming +td+ is an instance of TableDefinition
- # td.column(:granted, :boolean)
- # # granted BOOLEAN
- #
- # td.column(:picture, :binary, limit: 2.megabytes)
- # # => picture BLOB(2097152)
- #
- # td.column(:sales_stage, :string, limit: 20, default: 'new', null: false)
- # # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
- #
- # td.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
- # # => bill_gates_money DECIMAL(15,2)
#
- # td.column(:sensor_reading, :decimal, precision: 30, scale: 20)
- # # => sensor_reading DECIMAL(30,20)
- #
- # # While <tt>:scale</tt> defaults to zero on most databases, it
- # # probably wouldn't hurt to include it.
- # td.column(:huge_integer, :decimal, precision: 30)
- # # => huge_integer DECIMAL(30)
- #
- # # Defines a column with a database-specific type.
- # td.column(:foo, 'polygon')
- # # => foo polygon
+ # # Assuming +td+ is an instance of TableDefinition
+ # td.column(:granted, :boolean, index: true)
#
# == Short-hand examples
#
@@ -455,10 +388,6 @@ module ActiveRecord
ColumnDefinition.new name, type
end
- def native
- @native
- end
-
def aliased_types(name, fallback)
'timestamp' == name ? :datetime : fallback
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index d3fbc18f97..d5f8dbc8fc 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -446,12 +446,81 @@ module ActiveRecord
execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}"
end
- # Adds a new column to the named table.
- # See TableDefinition#column for details of the options you can use.
- #
- # Note: Not all options will be available, generally this command should
- # ignore most of them. In favor of doing a low-level call to simply
- # create a column.
+ # Add a new +type+ column named +column_name+ to +table_name+.
+ #
+ # The +type+ parameter is normally one of the migrations native types,
+ # which is one of the following:
+ # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
+ # <tt>:integer</tt>, <tt>:bigint</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
+ # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>,
+ # <tt>:binary</tt>, <tt>:boolean</tt>.
+ #
+ # You may use a type not in this list as long as it is supported by your
+ # database (for example, "polygon" in MySQL), but this will not be database
+ # agnostic and should usually be avoided.
+ #
+ # Available options are (none of these exists by default):
+ # * <tt>:limit</tt> -
+ # Requests a maximum column length. This is number of characters for a <tt>:string</tt> column
+ # and number of bytes for <tt>:text</tt>, <tt>:binary</tt> and <tt>:integer</tt> columns.
+ # * <tt>:default</tt> -
+ # The column's default value. Use nil for NULL.
+ # * <tt>:null</tt> -
+ # Allows or disallows +NULL+ values in the column. This option could
+ # have been named <tt>:null_allowed</tt>.
+ # * <tt>:precision</tt> -
+ # Specifies the precision for a <tt>:decimal</tt> column.
+ # * <tt>:scale</tt> -
+ # Specifies the scale for a <tt>:decimal</tt> column.
+ #
+ # Note: The precision is the total number of significant digits
+ # and the scale is the number of digits that can be stored following
+ # the decimal point. For example, the number 123.45 has a precision of 5
+ # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
+ # range from -999.99 to 999.99.
+ #
+ # Please be aware of different RDBMS implementations behavior with
+ # <tt>:decimal</tt> columns:
+ # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
+ # <tt>:precision</tt>, and makes no comments about the requirements of
+ # <tt>:precision</tt>.
+ # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
+ # Default is (10,0).
+ # * PostgreSQL: <tt>:precision</tt> [1..infinity],
+ # <tt>:scale</tt> [0..infinity]. No default.
+ # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
+ # Internal storage as strings. No default.
+ # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
+ # but the maximum supported <tt>:precision</tt> is 16. No default.
+ # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
+ # Default is (38,0).
+ # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
+ # Default unknown.
+ # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
+ # Default (38,0).
+ #
+ # == Examples
+ #
+ # add_column(:users, :picture, :binary, limit: 2.megabytes)
+ # # ALTER TABLE "users" ADD "picture" blob(2097152)
+ #
+ # add_column(:articles, :status, :string, limit: 20, default: 'draft', null: false)
+ # # ALTER TABLE "articles" ADD "status" varchar(20) DEFAULT 'draft' NOT NULL
+ #
+ # add_column(:answers, :bill_gates_money, :decimal, precision: 15, scale: 2)
+ # # ALTER TABLE "answers" ADD "bill_gates_money" decimal(15,2)
+ #
+ # add_column(:measurements, :sensor_reading, :decimal, precision: 30, scale: 20)
+ # # ALTER TABLE "measurements" ADD "sensor_reading" decimal(30,20)
+ #
+ # # While :scale defaults to zero on most databases, it
+ # # probably wouldn't hurt to include it.
+ # add_column(:measurements, :huge_integer, :decimal, precision: 30)
+ # # ALTER TABLE "measurements" ADD "huge_integer" decimal(30)
+ #
+ # # Defines a column with a database-specific type.
+ # add_column(:shapes, :triangle, 'polygon')
+ # # ALTER TABLE "shapes" ADD "triangle" polygon
def add_column(table_name, column_name, type, options = {})
at = create_alter_table table_name
at.add_column(column_name, type, options)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 9b46df721a..402159ac13 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -1,5 +1,6 @@
require 'active_record/type'
require 'active_support/core_ext/benchmark'
+require 'active_record/connection_adapters/determine_if_preparable_visitor'
require 'active_record/connection_adapters/schema_cache'
require 'active_record/connection_adapters/sql_type_metadata'
require 'active_record/connection_adapters/abstract/schema_dumper'
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
index f710ec10fc..251acf1c83 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -134,6 +134,7 @@ module ActiveRecord
time: { name: "time" },
date: { name: "date" },
binary: { name: "blob" },
+ blob: { name: "blob" },
boolean: { name: "tinyint", limit: 1 },
bigint: { name: "bigint" },
json: { name: "json" },
@@ -152,6 +153,7 @@ module ActiveRecord
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
@prepared_statements = true
+ @visitor.extend(DetermineIfPreparableVisitor)
else
@prepared_statements = false
end
@@ -167,6 +169,10 @@ module ActiveRecord
end
end
+ def version
+ @version ||= Version.new(full_version.match(/^\d+\.\d+\.\d+/)[0])
+ end
+
# Returns true, since this connection adapter supports migrations.
def supports_migrations?
true
@@ -477,7 +483,10 @@ module ActiveRecord
end
def tables(name = nil) # :nodoc:
- select_values("SHOW FULL TABLES", 'SCHEMA')
+ sql = "SELECT table_name FROM information_schema.tables "
+ sql << "WHERE table_schema = #{quote(@config[:database])}"
+
+ select_values(sql, 'SCHEMA')
end
alias data_sources tables
@@ -679,12 +688,18 @@ module ActiveRecord
# Maps logical Rails types to MySQL-specific data types.
def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil)
sql = case type.to_s
- when 'binary'
- binary_to_sql(limit)
when 'integer'
integer_to_sql(limit)
when 'text'
text_to_sql(limit)
+ when 'blob'
+ binary_to_sql(limit)
+ when 'binary'
+ if (0..0xfff) === limit
+ "varbinary(#{limit})"
+ else
+ binary_to_sql(limit)
+ end
else
super(type, limit, precision, scale)
end
@@ -924,10 +939,6 @@ module ActiveRecord
subselect.from subsubselect.distinct.as('__active_record_temp')
end
- def version
- @version ||= Version.new(full_version.match(/^\d+\.\d+\.\d+/)[0])
- end
-
def mariadb?
full_version =~ /mariadb/i
end
@@ -997,15 +1008,6 @@ module ActiveRecord
MySQL::TableDefinition.new(native_database_types, name, temporary, options, as)
end
- def binary_to_sql(limit) # :nodoc:
- case limit
- when 0..0xfff; "varbinary(#{limit})"
- when nil; "blob"
- when 0x1000..0xffffffff; "blob(#{limit})"
- else raise(ActiveRecordError, "No binary type has byte length #{limit}")
- end
- end
-
def integer_to_sql(limit) # :nodoc:
case limit
when 1; 'tinyint'
@@ -1028,6 +1030,16 @@ module ActiveRecord
end
end
+ def binary_to_sql(limit) # :nodoc:
+ case limit
+ when 0..0xff; 'tinyblob'
+ when nil, 0x100..0xffff; 'blob'
+ when 0x10000..0xffffff; 'mediumblob'
+ when 0x1000000..0xffffffff; 'longblob'
+ else raise(ActiveRecordError, "No binary type has byte length #{limit}")
+ end
+ end
+
class MysqlJson < Type::Internal::AbstractJson # :nodoc:
def changed_in_place?(raw_old_value, new_value)
# Normalization is required because MySQL JSON data format includes
diff --git a/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb b/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb
new file mode 100644
index 0000000000..0fdc185c45
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb
@@ -0,0 +1,22 @@
+module ActiveRecord
+ module ConnectionAdapters
+ module DetermineIfPreparableVisitor
+ attr_reader :preparable
+
+ def accept(*)
+ @preparable = true
+ super
+ end
+
+ def visit_Arel_Nodes_In(*)
+ @preparable = false
+ super
+ end
+
+ def visit_Arel_Nodes_SqlLiteral(*)
+ @preparable = false
+ super
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb
index bcf397cd77..29e8c73d46 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb
@@ -7,6 +7,10 @@ module ActiveRecord
super
end
+ def blob(*args, **options)
+ args.each { |name| column(name, :blob, options) }
+ end
+
def json(*args, **options)
args.each { |name| column(name, :json, options) }
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb
index 6448b8b5e2..3c48d0554e 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb
@@ -27,6 +27,14 @@ module ActiveRecord
private
+ def schema_type(column)
+ if column.sql_type == 'tinyblob'
+ 'blob'
+ else
+ super
+ end
+ end
+
def schema_limit(column)
super unless column.type == :boolean
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index 4461722bb4..42c4a14f00 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -126,7 +126,9 @@ module ActiveRecord
# Returns an array of arrays containing the field values.
# Order is the same as that returned by +columns+.
def select_rows(sql, name = nil, binds = [])
- execute(sql, name).to_a
+ result = execute(sql, name)
+ @connection.next_result while @connection.more_results?
+ result.to_a
end
# Executes the SQL statement in the context of this connection.
@@ -140,8 +142,9 @@ module ActiveRecord
super
end
- def exec_query(sql, name = 'SQL', binds = [])
+ def exec_query(sql, name = 'SQL', binds = [], prepare: false)
result = execute(sql, name)
+ @connection.next_result while @connection.more_results?
ActiveRecord::Result.new(result.fields, result.to_a)
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index b3894481cc..fddb318553 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -235,11 +235,11 @@ module ActiveRecord
@client_encoding = ENCODINGS[result.rows.last.last]
end
- def exec_query(sql, name = 'SQL', binds = [])
+ def exec_query(sql, name = 'SQL', binds = [], prepare: false)
if without_prepared_statement?(binds)
result_set, affected_rows = exec_without_stmt(sql, name)
else
- result_set, affected_rows = exec_stmt(sql, name, binds)
+ result_set, affected_rows = exec_stmt(sql, name, binds, cache_stmt: prepare)
end
yield affected_rows if block_given?
@@ -378,12 +378,12 @@ module ActiveRecord
private
- def exec_stmt(sql, name, binds)
+ def exec_stmt(sql, name, binds, cache_stmt: false)
cache = {}
type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
log(sql, name, binds) do
- if binds.empty?
+ if !cache_stmt
stmt = @connection.prepare(sql)
else
cache = @statements[sql] ||= {
@@ -399,7 +399,7 @@ module ActiveRecord
# place when an error occurs. To support older MySQL versions, we
# need to close the statement and delete the statement from the
# cache.
- if binds.empty?
+ if !cache_stmt
stmt.close
else
@statements.delete sql
@@ -417,7 +417,7 @@ module ActiveRecord
affected_rows = stmt.affected_rows
stmt.free_result
- stmt.close if binds.empty?
+ stmt.close if !cache_stmt
[result_set, affected_rows]
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
index 43e18ebb2b..0e0c0e993a 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
@@ -156,8 +156,8 @@ module ActiveRecord
end
end
- def exec_query(sql, name = 'SQL', binds = [])
- execute_and_clear(sql, name, binds) do |result|
+ def exec_query(sql, name = 'SQL', binds = [], prepare: false)
+ execute_and_clear(sql, name, binds, prepare: prepare) do |result|
types = {}
fields = result.fields
fields.each_with_index do |fname, i|
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 0686b35425..236c067fd5 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -198,6 +198,7 @@ module ActiveRecord
@visitor = Arel::Visitors::PostgreSQL.new self
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
@prepared_statements = true
+ @visitor.extend(DetermineIfPreparableVisitor)
else
@prepared_statements = false
end
@@ -553,16 +554,22 @@ module ActiveRecord
FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
- def execute_and_clear(sql, name, binds)
- result = without_prepared_statement?(binds) ? exec_no_cache(sql, name, binds) :
- exec_cache(sql, name, binds)
+ def execute_and_clear(sql, name, binds, prepare: false)
+ if without_prepared_statement?(binds)
+ result = exec_no_cache(sql, name, [])
+ elsif !prepare
+ result = exec_no_cache(sql, name, binds)
+ else
+ result = exec_cache(sql, name, binds)
+ end
ret = yield result
result.clear
ret
end
def exec_no_cache(sql, name, binds)
- log(sql, name, binds) { @connection.async_exec(sql, []) }
+ type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
+ log(sql, name, binds) { @connection.async_exec(sql, type_casted_binds) }
end
def exec_cache(sql, name, binds)
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 505a71720f..9028c1fcb9 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -89,6 +89,7 @@ module ActiveRecord
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
@prepared_statements = true
+ @visitor.extend(DetermineIfPreparableVisitor)
else
@prepared_statements = false
end
@@ -231,15 +232,18 @@ module ActiveRecord
end
end
- def exec_query(sql, name = nil, binds = [])
+ def exec_query(sql, name = nil, binds = [], prepare: false)
type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
log(sql, name, binds) do
# Don't cache statements if they are not prepared
- if without_prepared_statement?(binds)
+ unless prepare
stmt = @connection.prepare(sql)
begin
cols = stmt.columns
+ unless without_prepared_statement?(binds)
+ stmt.bind_params(type_casted_binds)
+ end
records = stmt.to_a
ensure
stmt.close
@@ -252,7 +256,7 @@ module ActiveRecord
stmt = cache[:stmt]
cols = cache[:cols] ||= stmt.columns
stmt.reset!
- stmt.bind_params type_casted_binds
+ stmt.bind_params(type_casted_binds)
end
ActiveRecord::Result.new(cols, stmt.to_a)
@@ -307,22 +311,18 @@ module ActiveRecord
# SCHEMA STATEMENTS ========================================
- def tables(name = nil, table_name = nil) #:nodoc:
- sql = <<-SQL
- SELECT name
- FROM sqlite_master
- WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence'
- SQL
- sql << " AND name = #{quote_table_name(table_name)}" if table_name
-
- exec_query(sql, 'SCHEMA').map do |row|
- row['name']
- end
+ def tables(name = nil) # :nodoc:
+ select_values("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'", 'SCHEMA')
end
alias data_sources tables
def table_exists?(table_name)
- table_name && tables(nil, table_name).any?
+ return false unless table_name.present?
+
+ sql = "SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'"
+ sql << " AND name = #{quote(table_name)}"
+
+ select_values(sql, 'SCHEMA').any?
end
alias data_source_exists? table_exists?
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index db3e9d1d52..142b6e8599 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -177,7 +177,7 @@ module ActiveRecord
hash = args.first
return super if hash.values.any? { |v|
- v.nil? || Array === v || Hash === v
+ v.nil? || Array === v || Hash === v || Relation === v
}
# We can't cache Post.find_by(author: david) ...yet
diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb
index 9adabd7819..90bcf5a205 100644
--- a/activerecord/lib/active_record/explain_subscriber.rb
+++ b/activerecord/lib/active_record/explain_subscriber.rb
@@ -14,7 +14,7 @@ module ActiveRecord
end
# SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
- # our own EXPLAINs now matter how loopingly beautiful that would be.
+ # our own EXPLAINs no matter how loopingly beautiful that would be.
#
# On the other hand, we want to monitor the performance of our real database
# queries, not the performance of the access to the query cache.
diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb
index 19d2589db3..466c8509a4 100644
--- a/activerecord/lib/active_record/integration.rb
+++ b/activerecord/lib/active_record/integration.rb
@@ -10,9 +10,9 @@ module ActiveRecord
# Indicates the format used to generate the timestamp in the cache key.
# Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
#
- # This is +:nsec+, by default.
+ # This is +:usec+, by default.
class_attribute :cache_timestamp_format, :instance_writer => false
- self.cache_timestamp_format = :nsec
+ self.cache_timestamp_format = :usec
end
# Returns a String, which Action Pack uses for constructing a URL to this
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 90b8a29869..c8b96b8de0 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -194,17 +194,18 @@ module ActiveRecord
#
# == Available transformations
#
+ # === Creation
+ #
+ # * <tt>create_join_table(table_1, table_2, options)</tt>: Creates a join
+ # table having its name as the lexical order of the first two
+ # arguments. See
+ # ActiveRecord::ConnectionAdapters::SchemaStatements#create_join_table for
+ # details.
# * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
# makes the table object available to a block that can then add columns to it,
# following the same format as +add_column+. See example above. The options hash
# is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
# table definition.
- # * <tt>drop_table(name)</tt>: Drops the table called +name+.
- # * <tt>change_table(name, options)</tt>: Allows to make column alterations to
- # the table called +name+. It makes the table object available to a block that
- # can then add/remove columns, indexes or foreign keys to it.
- # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
- # to +new_name+.
# * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
# to the table called +table_name+
# named +column_name+ specified to be one of the following types:
@@ -215,24 +216,59 @@ module ActiveRecord
# Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
# <tt>{ limit: 50, null: false }</tt>) -- see
# ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
- # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
- # a column but keeps the type and content.
- # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
- # the column to a different type using the same parameters as add_column.
- # * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column
- # named +column_name+ from the table called +table_name+.
+ # * <tt>add_foreign_key(from_table, to_table, options)</tt>: Adds a new
+ # foreign key. +from_table+ is the table with the key column, +to_table+ contains
+ # the referenced primary key.
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
# with the name of the column. Other options include
# <tt>:name</tt>, <tt>:unique</tt> (e.g.
# <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
# (e.g. <tt>{ order: { name: :desc } }</tt>).
+ # * <tt>add_reference(:table_name, :reference_name)</tt>: Adds a new column
+ # +reference_name_id+ by default an integer. See
+ # ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference for details.
+ # * <tt>add_timestamps(table_name, options)</tt>: Adds timestamps (+created_at+
+ # and +updated_at+) columns to +table_name+.
+ #
+ # === Modification
+ #
+ # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
+ # the column to a different type using the same parameters as add_column.
+ # * <tt>change_column_default(table_name, column_name, default)</tt>: Sets a
+ # default value for +column_name+ definded by +default+ on +table_name+.
+ # * <tt>change_column_null(table_name, column_name, null, default = nil)</tt>:
+ # Sets or removes a +NOT NULL+ constraint on +column_name+. The +null+ flag
+ # indicates whether the value can be +NULL+. See
+ # ActiveRecord::ConnectionAdapters::SchemaStatements#change_column_null for
+ # details.
+ # * <tt>change_table(name, options)</tt>: Allows to make column alterations to
+ # the table called +name+. It makes the table object available to a block that
+ # can then add/remove columns, indexes or foreign keys to it.
+ # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
+ # a column but keeps the type and content.
+ # * <tt>rename_index(table_name, old_name, new_name)</tt>: Renames an index.
+ # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
+ # to +new_name+.
+ #
+ # === Deletion
+ #
+ # * <tt>drop_table(name)</tt>: Drops the table called +name+.
+ # * <tt>drop_join_table(table_1, table_2, options)</tt>: Drops the join table
+ # specified by the given arguments.
+ # * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column
+ # named +column_name+ from the table called +table_name+.
+ # * <tt>remove_columns(table_name, *column_names)</tt>: Removes the given
+ # columns from the table definition.
+ # * <tt>remove_foreign_key(from_table, options_or_to_table)</tt>: Removes the
+ # given foreign key from the table called +table_name+.
# * <tt>remove_index(table_name, column: column_names)</tt>: Removes the index
# specified by +column_names+.
# * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
# specified by +index_name+.
- # * <tt>add_reference(:table_name, :reference_name)</tt>: Adds a new column
- # +reference_name_id+ by default an integer. See
- # ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference for details.
+ # * <tt>remove_reference(table_name, ref_name, options)</tt>: Removes the
+ # reference(s) on +table_name+ specified by +ref_name+.
+ # * <tt>remove_timestamps(table_name, options)</tt>: Removes the timestamp
+ # columns (+created_at+ and +updated_at+) from the table definition.
#
# == Irreversible transformations
#
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index d940ac244a..b6f3695856 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -34,7 +34,7 @@ db_namespace = namespace :db do
end
end
- # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
+ # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:purge:all to purge all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
task :purge => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.purge_current
end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 16d5774fec..f45844a9ea 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -219,6 +219,8 @@ module ActiveRecord
end
def aggregate_column(column_name)
+ return column_name if Arel::Expressions === column_name
+
if @klass.column_names.include?(column_name.to_s)
Arel::Attribute.new(@klass.unscoped.table, column_name)
else
@@ -273,15 +275,10 @@ module ActiveRecord
else
group_fields = group_attrs
end
+ group_fields = arel_columns(group_fields)
- group_aliases = group_fields.map { |field|
- column_alias_for(field)
- }
- group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
- [aliaz, field]
- }
-
- group = group_fields
+ group_aliases = group_fields.map { |field| column_alias_for(field) }
+ group_columns = group_aliases.zip(group_fields)
if operation == 'count' && column_name == :all
aggregate_alias = 'count_all'
@@ -297,7 +294,7 @@ module ActiveRecord
]
select_values += select_values unless having_clause.empty?
- select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
+ select_values.concat group_columns.map { |aliaz, field|
if field.respond_to?(:as)
field.as(aliaz)
else
@@ -306,7 +303,7 @@ module ActiveRecord
}
relation = except(:group)
- relation.group_values = group
+ relation.group_values = group_fields
relation.select_values = select_values
calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes)
@@ -367,9 +364,9 @@ module ActiveRecord
end
end
- # TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
def select_for_count
if select_values.present?
+ return select_values.first if select_values.one?
select_values.join(", ")
else
:all
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 0dcecbd42d..f5afc1000d 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -375,7 +375,7 @@ module ActiveRecord
#
# This means it can be used in association definitions:
#
- # has_many :comments, -> { unscope where: :trashed }
+ # has_many :comments, -> { unscope(where: :trashed) }
#
def unscope(*args)
check_if_method_has_arguments!(:unscope, args)
@@ -552,8 +552,6 @@ module ActiveRecord
WhereChain.new(spawn)
elsif opts.blank?
self
- elsif !opts.is_a?(String) && !opts.respond_to?(:to_h)
- raise ArgumentError, "Unsupported argument type: #{opts} (#{opts.class})"
else
spawn.where!(opts, *rest)
end
diff --git a/activerecord/lib/active_record/relation/where_clause_factory.rb b/activerecord/lib/active_record/relation/where_clause_factory.rb
index 83ac074f97..a81ff98e49 100644
--- a/activerecord/lib/active_record/relation/where_clause_factory.rb
+++ b/activerecord/lib/active_record/relation/where_clause_factory.rb
@@ -20,8 +20,10 @@ module ActiveRecord
attributes, binds = predicate_builder.create_binds(attributes)
parts = predicate_builder.build_from_hash(attributes)
- else
+ when Arel::Nodes::Node
parts = [opts]
+ else
+ raise ArgumentError, "Unsupported argument type: #{opts} (#{opts.class})"
end
WhereClause.new(parts, binds)
diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb
index 17bc066e4d..cdcb73382f 100644
--- a/activerecord/lib/active_record/scoping/default.rb
+++ b/activerecord/lib/active_record/scoping/default.rb
@@ -17,7 +17,7 @@ module ActiveRecord
#
# class Post < ActiveRecord::Base
# def self.default_scope
- # where published: true
+ # where(published: true)
# end
# end
#
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
index ea7927a435..c0c29a618c 100644
--- a/activerecord/lib/active_record/tasks/database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -94,8 +94,9 @@ module ActiveRecord
rescue DatabaseAlreadyExists
$stderr.puts "#{configuration['database']} already exists"
rescue Exception => error
- $stderr.puts error, *(error.backtrace)
+ $stderr.puts error
$stderr.puts "Couldn't create database for #{configuration.inspect}"
+ raise
end
def create_all
@@ -115,8 +116,9 @@ module ActiveRecord
rescue ActiveRecord::NoDatabaseError
$stderr.puts "Database '#{configuration['database']}' does not exist"
rescue Exception => error
- $stderr.puts error, *(error.backtrace)
+ $stderr.puts error
$stderr.puts "Couldn't drop #{configuration['database']}"
+ raise
end
def drop_all
diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
index 9ab64d0325..9ec3c8a94a 100644
--- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
@@ -19,11 +19,15 @@ module ActiveRecord
path = Pathname.new configuration['database']
file = path.absolute? ? path.to_s : File.join(root, path)
- FileUtils.rm(file) if File.exist?(file)
+ FileUtils.rm(file)
+ rescue Errno::ENOENT => error
+ raise NoDatabaseError.new(error.message, error)
end
def purge
drop
+ rescue NoDatabaseError
+ ensure
create
end
diff --git a/activerecord/lib/rails/generators/active_record/migration.rb b/activerecord/lib/rails/generators/active_record/migration.rb
index b7418cf42f..c2b2209638 100644
--- a/activerecord/lib/rails/generators/active_record/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration.rb
@@ -13,6 +13,13 @@ module ActiveRecord
ActiveRecord::Migration.next_migration_number(next_migration_number)
end
end
+
+ private
+
+ def primary_key_type
+ key_type = options[:primary_key_type]
+ ", id: :#{key_type}" if key_type
+ end
end
end
end
diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
index 0d57de4d65..4e5872b585 100644
--- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
@@ -5,6 +5,8 @@ module ActiveRecord
class MigrationGenerator < Base # :nodoc:
argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
+ class_option :primary_key_type, type: :string, desc: "The type for primary key"
+
def create_migration_file
set_local_assigns!
validate_file_name!
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
index 5b3e57dcf6..fadab2a1e6 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
@@ -1,6 +1,6 @@
class <%= migration_class_name %> < ActiveRecord::Migration
def change
- create_table :<%= table_name %> do |t|
+ create_table :<%= table_name %><%= primary_key_type %> do |t|
<% attributes.each do |attribute| -%>
<% if attribute.password_digest? -%>
t.string :password_digest<%= attribute.inject_options %>
diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
index 7e8d68ce69..395951ac9d 100644
--- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
@@ -7,14 +7,13 @@ module ActiveRecord
check_class_collision
- class_option :migration, :type => :boolean
- class_option :timestamps, :type => :boolean
- class_option :parent, :type => :string, :desc => "The parent class for the generated model"
- class_option :indexes, :type => :boolean, :default => true, :desc => "Add indexes for references and belongs_to columns"
+ class_option :migration, type: :boolean
+ class_option :timestamps, type: :boolean
+ class_option :parent, type: :string, desc: "The parent class for the generated model"
+ class_option :indexes, type: :boolean, default: true, desc: "Add indexes for references and belongs_to columns"
+ class_option :primary_key_type, type: :string, desc: "The type for primary key"
-
# creates the migration file for the model.
-
def create_migration_file
return unless options[:migration] && options[:parent].nil?
attributes.each { |a| a.attr_options.delete(:index) if a.reference? && !a.has_index? } if options[:indexes] == false
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
index 5699fa110f..decac9e83b 100644
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -118,15 +118,6 @@ class MysqlConnectionTest < ActiveRecord::MysqlTestCase
end
end
- # Test that MySQL allows multiple results for stored procedures
- if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
- def test_multi_results
- rows = ActiveRecord::Base.connection.select_rows('CALL ten();')
- assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
- assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'"
- end
- end
-
def test_mysql_connection_collation_is_configured
assert_equal 'utf8_unicode_ci', @connection.show_variable('collation_connection')
assert_equal 'utf8_general_ci', ARUnit2Model.connection.show_variable('collation_connection')
diff --git a/activerecord/test/cases/adapters/mysql/sp_test.rb b/activerecord/test/cases/adapters/mysql/sp_test.rb
index a3d5110032..579c3273c6 100644
--- a/activerecord/test/cases/adapters/mysql/sp_test.rb
+++ b/activerecord/test/cases/adapters/mysql/sp_test.rb
@@ -1,15 +1,29 @@
require "cases/helper"
require 'models/topic'
+require 'models/reply'
-class StoredProcedureTest < ActiveRecord::MysqlTestCase
+class MysqlStoredProcedureTest < ActiveRecord::MysqlTestCase
fixtures :topics
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
# Test that MySQL allows multiple results for stored procedures
- if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
+ #
+ # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default.
+ # http://dev.mysql.com/doc/refman/5.6/en/call.html
+ if ActiveRecord::Base.connection.version >= '5.6.0' || Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
+ def test_multi_results
+ rows = @connection.select_rows('CALL ten();')
+ assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
+ assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'"
+ end
+
def test_multi_results_from_find_by_sql
- topics = Topic.find_by_sql 'CALL topics();'
- assert_equal 1, topics.size
- assert ActiveRecord::Base.connection.active?, "Bad connection use by 'MysqlAdapter.select'"
+ topics = Topic.find_by_sql 'CALL topics(3);'
+ assert_equal 3, topics.size
+ assert @connection.active?, "Bad connection use by 'MysqlAdapter.select'"
end
end
end
diff --git a/activerecord/test/cases/adapters/mysql/sql_types_test.rb b/activerecord/test/cases/adapters/mysql/sql_types_test.rb
index 25b28de7f0..d18579f242 100644
--- a/activerecord/test/cases/adapters/mysql/sql_types_test.rb
+++ b/activerecord/test/cases/adapters/mysql/sql_types_test.rb
@@ -4,7 +4,7 @@ class MysqlSqlTypesTest < ActiveRecord::MysqlTestCase
def test_binary_types
assert_equal 'varbinary(64)', type_to_sql(:binary, 64)
assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095)
- assert_equal 'blob(4096)', type_to_sql(:binary, 4096)
+ assert_equal 'blob', type_to_sql(:binary, 4096)
assert_equal 'blob', type_to_sql(:binary)
end
diff --git a/activerecord/test/cases/adapters/mysql2/sp_test.rb b/activerecord/test/cases/adapters/mysql2/sp_test.rb
new file mode 100644
index 0000000000..8b12945f24
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/sp_test.rb
@@ -0,0 +1,29 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+
+class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase
+ fixtures :topics
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
+ # Test that MySQL allows multiple results for stored procedures
+ #
+ # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default.
+ # http://dev.mysql.com/doc/refman/5.6/en/call.html
+ if ActiveRecord::Base.connection.version >= '5.6.0'
+ def test_multi_results
+ rows = @connection.select_rows('CALL ten();')
+ assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
+ assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_rows'"
+ end
+
+ def test_multi_results_from_find_by_sql
+ topics = Topic.find_by_sql 'CALL topics(3);'
+ assert_equal 3, topics.size
+ assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select'"
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb
index ae505d29c9..4926bc2267 100644
--- a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb
@@ -4,7 +4,7 @@ class Mysql2SqlTypesTest < ActiveRecord::Mysql2TestCase
def test_binary_types
assert_equal 'varbinary(64)', type_to_sql(:binary, 64)
assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095)
- assert_equal 'blob(4096)', type_to_sql(:binary, 4096)
+ assert_equal 'blob', type_to_sql(:binary, 4096)
assert_equal 'blob', type_to_sql(:binary)
end
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index 820d41e13b..722e2377c1 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -127,7 +127,7 @@ module ActiveRecord
def test_statement_key_is_logged
bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new)
- @connection.exec_query('SELECT $1::integer', 'SQL', [bind])
+ @connection.exec_query('SELECT $1::integer', 'SQL', [bind], prepare: true)
name = @subscriber.payloads.last[:statement_name]
assert name
res = @connection.exec_query("EXPLAIN (FORMAT JSON) EXECUTE #{name}(1)")
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index f89a394f96..93e98ec872 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -168,7 +168,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase
def test_raise_wraped_exception_on_bad_prepare
assert_raises(ActiveRecord::StatementInvalid) do
- @connection.exec_query "select * from developers where id = ?", 'sql', [[nil, 1]]
+ @connection.exec_query "select * from developers where id = ?", 'sql', [bind_param(1)]
end
end
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 77d99bc116..640df31e2e 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -294,7 +294,7 @@ module ActiveRecord
def test_tables_logs_name
sql = <<-SQL
SELECT name FROM sqlite_master
- WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence'
+ WHERE type IN ('table','view') AND name <> 'sqlite_sequence'
SQL
assert_logged [[sql.squish, 'SCHEMA', []]] do
@conn.tables('hello')
@@ -313,8 +313,7 @@ module ActiveRecord
with_example_table do
sql = <<-SQL
SELECT name FROM sqlite_master
- WHERE (type = 'table' OR type = 'view')
- AND NOT name = 'sqlite_sequence' AND name = \"ex\"
+ WHERE type IN ('table','view') AND name <> 'sqlite_sequence' AND name = 'ex'
SQL
assert_logged [[sql.squish, 'SCHEMA', []]] do
assert @conn.table_exists?('ex')
diff --git a/activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb b/activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb
new file mode 100644
index 0000000000..2b867965ba
--- /dev/null
+++ b/activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb
@@ -0,0 +1,41 @@
+require 'cases/helper'
+require 'models/content'
+
+class BidirectionalDestroyDependenciesTest < ActiveRecord::TestCase
+ fixtures :content, :content_positions
+
+ def setup
+ Content.destroyed_ids.clear
+ ContentPosition.destroyed_ids.clear
+ end
+
+ def test_bidirectional_dependence_when_destroying_item_with_belongs_to_association
+ content_position = ContentPosition.find(1)
+ content = content_position.content
+ assert_not_nil content
+
+ content_position.destroy
+
+ assert_equal [content_position.id], ContentPosition.destroyed_ids
+ assert_equal [content.id], Content.destroyed_ids
+ end
+
+ def test_bidirectional_dependence_when_destroying_item_with_has_one_association
+ content = Content.find(1)
+ content_position = content.content_position
+ assert_not_nil content_position
+
+ content.destroy
+
+ assert_equal [content.id], Content.destroyed_ids
+ assert_equal [content_position.id], ContentPosition.destroyed_ids
+ end
+
+ def test_bidirectional_dependence_when_destroying_item_with_has_one_association_fails_first_time
+ content = ContentWhichRequiresTwoDestroyCalls.find(1)
+
+ 2.times { content.destroy }
+
+ assert_equal content.destroyed?, true
+ end
+end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index ddfb856a05..bc1bff79d3 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -24,6 +24,8 @@ require 'models/membership'
require 'models/club'
require 'models/categorization'
require 'models/sponsor'
+require 'models/mentor'
+require 'models/contract'
class EagerAssociationTest < ActiveRecord::TestCase
fixtures :posts, :comments, :authors, :essays, :author_addresses, :categories, :categories_posts,
@@ -1218,6 +1220,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
end
+ def test_eager_load_multiple_associations_with_references
+ mentor = Mentor.create!(name: "Barış Can DAYLIK")
+ developer = Developer.create!(name: "Mehmet Emin İNAÇ", mentor: mentor)
+ Contract.create!(developer: developer)
+ project = Project.create!(name: "VNGRS", mentor: mentor)
+ project.developers << developer
+ projects = Project.references(:mentors).includes(mentor: { developers: :contracts }, developers: :contracts)
+ assert_equal projects.last.mentor.developers.first.contracts, projects.last.developers.last.contracts
+ end
+
test "scoping with a circular preload" do
assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 20af436e02..e9f679e6de 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -957,4 +957,23 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
projects = ProjectUnscopingDavidDefaultScope.includes(:developers).where(id: project.id)
assert_equal 1, projects.first.developers.size
end
+
+ def test_preloaded_associations_size
+ assert_equal Project.first.salaried_developers.size,
+ Project.preload(:salaried_developers).first.salaried_developers.size
+
+ assert_equal Project.includes(:salaried_developers).references(:salaried_developers).first.salaried_developers.size,
+ Project.preload(:salaried_developers).first.salaried_developers.size
+
+ # Nested HATBM
+ first_project = Developer.first.projects.first
+ preloaded_first_project =
+ Developer.preload(projects: :salaried_developers).
+ first.
+ projects.
+ detect { |p| p.id == first_project.id }
+
+ assert preloaded_first_project.salaried_developers.loaded?, true
+ assert_equal first_project.salaried_developers.size, preloaded_first_project.salaried_developers.size
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index cd19a7a5bc..eb94870a35 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -2181,6 +2181,26 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id)
end
+ test "can unscope and where the default scope of the associated model" do
+ Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: 'other') }, class_name: "Bulb"
+ car = Car.create!
+ bulb1 = Bulb.create! name: "defaulty", car: car
+ bulb2 = Bulb.create! name: "other", car: car
+
+ assert_equal [bulb1], car.bulbs
+ assert_equal [bulb2], car.other_bulbs
+ end
+
+ test "can rewhere the default scope of the associated model" do
+ Car.has_many :old_bulbs, -> { rewhere(name: 'old') }, class_name: "Bulb"
+ car = Car.create!
+ bulb1 = Bulb.create! name: "defaulty", car: car
+ bulb2 = Bulb.create! name: "old", car: car
+
+ assert_equal [bulb1], car.bulbs
+ assert_equal [bulb2], car.old_bulbs
+ end
+
test 'unscopes the default scope of associated model when used with include' do
car = Car.create!
bulb = Bulb.create! name: "other", car: car
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index ece4dab539..57d1c8feda 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -83,10 +83,10 @@ class AutomaticInverseFindingTests < ActiveRecord::TestCase
assert_equal rating.comment, comment, "The Rating's comment should be the original Comment"
- rating.comment.body = "Brogramming is the act of programming, like a bro."
+ rating.comment.body = "Fennec foxes are the smallest of the foxes."
assert_equal rating.comment.body, comment.body, "Changing the Comment's body on the association should change the original Comment's body"
- comment.body = "Broseiden is the king of the sea of bros."
+ comment.body = "Kittens are adorable."
assert_equal comment.body, rating.comment.body, "Changing the original Comment's body should change the Comment's body on the association"
end
@@ -97,10 +97,10 @@ class AutomaticInverseFindingTests < ActiveRecord::TestCase
assert_equal rating.comment, comment, "The Rating's comment should be the original Comment"
- rating.comment.body = "Brogramming is the act of programming, like a bro."
+ rating.comment.body = "Fennec foxes are the smallest of the foxes."
assert_equal rating.comment.body, comment.body, "Changing the Comment's body on the association should change the original Comment's body"
- comment.body = "Broseiden is the king of the sea of bros."
+ comment.body = "Kittens are adorable."
assert_equal comment.body, rating.comment.body, "Changing the original Comment's body should change the Comment's body on the association"
end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 37ec3f1106..0df8f1f798 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -24,6 +24,8 @@ require 'models/molecule'
require 'models/member'
require 'models/member_detail'
require 'models/organization'
+require 'models/guitar'
+require 'models/tuning_peg'
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
def test_autosave_validation
@@ -397,6 +399,40 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttrib
assert_not molecule.persisted?, 'Molecule should not be persisted when its electrons are invalid'
end
+ def test_errors_should_be_indexed_when_passed_as_array
+ guitar = Guitar.new
+ tuning_peg_valid = TuningPeg.new
+ tuning_peg_valid.pitch = 440.0
+ tuning_peg_invalid = TuningPeg.new
+
+ guitar.tuning_pegs = [tuning_peg_valid, tuning_peg_invalid]
+
+ assert_not tuning_peg_invalid.valid?
+ assert tuning_peg_valid.valid?
+ assert_not guitar.valid?
+ assert_equal ["is not a number"], guitar.errors["tuning_pegs[1].pitch"]
+ assert_not_equal ["is not a number"], guitar.errors["tuning_pegs.pitch"]
+ end
+
+ def test_errors_should_be_indexed_when_global_flag_is_set
+ old_attribute_config = ActiveRecord::Base.index_nested_attribute_errors
+ ActiveRecord::Base.index_nested_attribute_errors = true
+
+ molecule = Molecule.new
+ valid_electron = Electron.new(name: 'electron')
+ invalid_electron = Electron.new
+
+ molecule.electrons = [valid_electron, invalid_electron]
+
+ assert_not invalid_electron.valid?
+ assert valid_electron.valid?
+ assert_not molecule.valid?
+ assert_equal ["can't be blank"], molecule.errors["electrons[1].name"]
+ assert_not_equal ["can't be blank"], molecule.errors["electrons.name"]
+ ensure
+ ActiveRecord::Base.index_nested_attribute_errors = old_attribute_config
+ end
+
def test_valid_adding_with_nested_attributes
molecule = Molecule.new
valid_electron = Electron.new(name: 'electron')
diff --git a/activerecord/test/cases/cache_key_test.rb b/activerecord/test/cases/cache_key_test.rb
new file mode 100644
index 0000000000..bb2829b3c1
--- /dev/null
+++ b/activerecord/test/cases/cache_key_test.rb
@@ -0,0 +1,25 @@
+require "cases/helper"
+
+module ActiveRecord
+ class CacheKeyTest < ActiveRecord::TestCase
+ self.use_transactional_tests = false
+
+ class CacheMe < ActiveRecord::Base; end
+
+ setup do
+ @connection = ActiveRecord::Base.connection
+ @connection.create_table(:cache_mes) { |t| t.timestamps }
+ end
+
+ teardown do
+ @connection.drop_table :cache_mes, if_exists: true
+ end
+
+ test "test_cache_key_format_is_not_too_precise" do
+ record = CacheMe.create
+ key = record.cache_key
+
+ assert_equal key, record.reload.cache_key
+ end
+ end
+end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index d904b802fa..4a0e6f497f 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -31,11 +31,20 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 318, Account.sum(:credit_limit)
end
+ def test_should_sum_arel_attribute
+ assert_equal 318, Account.sum(Account.arel_table[:credit_limit])
+ end
+
def test_should_average_field
value = Account.average(:credit_limit)
assert_equal 53.0, value
end
+ def test_should_average_arel_attribute
+ value = Account.average(Account.arel_table[:credit_limit])
+ assert_equal 53.0, value
+ end
+
def test_should_resolve_aliased_attributes
assert_equal 318, Account.sum(:available_credit)
end
@@ -60,14 +69,26 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 60, Account.maximum(:credit_limit)
end
+ def test_should_get_maximum_of_arel_attribute
+ assert_equal 60, Account.maximum(Account.arel_table[:credit_limit])
+ end
+
def test_should_get_maximum_of_field_with_include
assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(:credit_limit)
end
+ def test_should_get_maximum_of_arel_attribute_with_include
+ assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(Account.arel_table[:credit_limit])
+ end
+
def test_should_get_minimum_of_field
assert_equal 50, Account.minimum(:credit_limit)
end
+ def test_should_get_minimum_of_arel_attribute
+ assert_equal 50, Account.minimum(Account.arel_table[:credit_limit])
+ end
+
def test_should_group_by_field
c = Account.group(:firm_id).sum(:credit_limit)
[1,6,2].each do |firm_id|
@@ -102,6 +123,25 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 60, c[2]
end
+ def test_should_generate_valid_sql_with_joins_and_group
+ assert_nothing_raised ActiveRecord::StatementInvalid do
+ AuditLog.joins(:developer).group(:id).count
+ end
+ end
+
+ def test_should_calculate_against_given_relation
+ developer = Developer.create!(name: "developer")
+ developer.audit_logs.create!(message: "first log")
+ developer.audit_logs.create!(message: "second log")
+
+ c = developer.audit_logs.joins(:developer).group(:id).count
+
+ assert_equal developer.audit_logs.count, c.size
+ developer.audit_logs.each do |log|
+ assert_equal 1, c[log.id]
+ end
+ end
+
def test_should_order_by_grouped_field
c = Account.group(:firm_id).order("firm_id").sum(:credit_limit)
assert_equal [1, 2, 6, 9], c.keys.compact
@@ -131,6 +171,14 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 3, accounts.select(:firm_id).count
end
+ def test_limit_should_apply_before_count_arel_attribute
+ accounts = Account.limit(3).where('firm_id IS NOT NULL')
+
+ firm_id_attribute = Account.arel_table[:firm_id]
+ assert_equal 3, accounts.count(firm_id_attribute)
+ assert_equal 3, accounts.select(firm_id_attribute).count
+ end
+
def test_count_should_shortcut_with_limit_zero
accounts = Account.limit(0)
@@ -353,10 +401,23 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 6, Account.select("DISTINCT accounts.id").includes(:firm).count
end
+ def test_count_selected_arel_attribute
+ assert_equal 5, Account.select(Account.arel_table[:firm_id]).count
+ assert_equal 4, Account.distinct.select(Account.arel_table[:firm_id]).count
+ end
+
def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end
+ def test_count_with_arel_attribute
+ assert_equal 5, Account.count(Account.arel_table[:firm_id])
+ end
+
+ def test_count_with_arel_star
+ assert_equal 6, Account.count(Arel.star)
+ end
+
def test_count_with_distinct
assert_equal 4, Account.select(:credit_limit).distinct.count
@@ -378,12 +439,27 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 4, Account.joins(:firm).distinct.count('companies.id')
end
+ def test_count_arel_attribute_in_joined_table_with
+ assert_equal 5, Account.joins(:firm).count(Company.arel_table[:id])
+ assert_equal 4, Account.joins(:firm).distinct.count(Company.arel_table[:id])
+ end
+
+ def test_count_selected_arel_attribute_in_joined_table
+ assert_equal 5, Account.joins(:firm).select(Company.arel_table[:id]).count
+ assert_equal 4, Account.joins(:firm).distinct.select(Company.arel_table[:id]).count
+ end
+
def test_should_count_field_in_joined_table_with_group_by
c = Account.group('accounts.firm_id').joins(:firm).count('companies.id')
[1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
end
+ def test_should_count_field_of_root_table_with_conflicting_group_by_column
+ assert_equal({ 1 => 1 }, Firm.joins(:accounts).group(:firm_id).count)
+ assert_equal({ 1 => 1 }, Firm.joins(:accounts).group('accounts.firm_id').count)
+ end
+
def test_count_with_no_parameters_isnt_deprecated
assert_not_deprecated { Account.count }
end
diff --git a/activerecord/test/cases/collection_cache_key_test.rb b/activerecord/test/cases/collection_cache_key_test.rb
index 724234d7f4..53058c5a4a 100644
--- a/activerecord/test/cases/collection_cache_key_test.rb
+++ b/activerecord/test/cases/collection_cache_key_test.rb
@@ -53,7 +53,7 @@ module ActiveRecord
test "cache_key with custom timestamp column" do
topics = Topic.where("title like ?", "%Topic%")
- last_topic_timestamp = topics(:fifth).written_on.utc.to_s(:nsec)
+ last_topic_timestamp = topics(:fifth).written_on.utc.to_s(:usec)
assert_match(last_topic_timestamp, topics.cache_key(:written_on))
end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 307b68764e..6686ce012d 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -265,6 +265,12 @@ class FinderTest < ActiveRecord::TestCase
assert_equal [Account], accounts.collect(&:class).uniq
end
+ def test_find_by_association_subquery
+ author = authors(:david)
+ assert_equal author.post, Post.find_by(author: Author.where(id: author))
+ assert_equal author.post, Post.find_by(author_id: Author.where(id: author))
+ end
+
def test_take
assert_equal topics(:first), Topic.take
end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index 89bd3f888e..d82a3040fc 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -47,7 +47,7 @@ def in_memory_db?
end
def subsecond_precision_supported?
- !current_adapter?(:MysqlAdapter, :Mysql2Adapter) || ActiveRecord::Base.connection.send(:version) >= '5.6.4'
+ !current_adapter?(:MysqlAdapter, :Mysql2Adapter) || ActiveRecord::Base.connection.version >= '5.6.4'
end
def mysql_enforcing_gtid_consistency?
diff --git a/activerecord/test/cases/integration_test.rb b/activerecord/test/cases/integration_test.rb
index 9169207b0a..08a186ae07 100644
--- a/activerecord/test/cases/integration_test.rb
+++ b/activerecord/test/cases/integration_test.rb
@@ -81,7 +81,7 @@ class IntegrationTest < ActiveRecord::TestCase
def test_cache_key_format_for_existing_record_with_updated_at
dev = Developer.first
- assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key
+ assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:usec)}", dev.cache_key
end
def test_cache_key_format_for_existing_record_with_updated_at_and_custom_cache_timestamp_format
@@ -111,19 +111,19 @@ class IntegrationTest < ActiveRecord::TestCase
def test_cache_key_for_updated_on
dev = Developer.first
dev.updated_at = nil
- assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:nsec)}", dev.cache_key
+ assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:usec)}", dev.cache_key
end
def test_cache_key_for_newer_updated_at
dev = Developer.first
dev.updated_at += 3600
- assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key
+ assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:usec)}", dev.cache_key
end
def test_cache_key_for_newer_updated_on
dev = Developer.first
dev.updated_on += 3600
- assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:nsec)}", dev.cache_key
+ assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:usec)}", dev.cache_key
end
def test_cache_key_format_is_precise_enough
@@ -134,8 +134,16 @@ class IntegrationTest < ActiveRecord::TestCase
assert_not_equal key, dev.cache_key
end
+ def test_cache_key_format_is_not_too_precise
+ skip("Subsecond precision is not supported") unless subsecond_precision_supported?
+ dev = Developer.first
+ dev.touch
+ key = dev.cache_key
+ assert_equal key, dev.reload.cache_key
+ end
+
def test_named_timestamps_for_cache_key
owner = owners(:blackbeard)
- assert_equal "owners/#{owner.id}-#{owner.happy_at.utc.to_s(:nsec)}", owner.cache_key(:updated_at, :happy_at)
+ assert_equal "owners/#{owner.id}-#{owner.happy_at.utc.to_s(:usec)}", owner.cache_key(:updated_at, :happy_at)
end
end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index b0fb905760..675149556f 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -57,9 +57,6 @@ module ActiveRecord
def test_empty_where_values_hash
relation = Relation.new(FakeKlass, :b, nil)
assert_equal({}, relation.where_values_hash)
-
- relation.where! :hello
- assert_equal({}, relation.where_values_hash)
end
def test_has_values
@@ -153,10 +150,10 @@ module ActiveRecord
end
test 'merging a hash into a relation' do
- relation = Relation.new(FakeKlass, :b, nil)
- relation = relation.merge where: :lol, readonly: true
+ relation = Relation.new(Post, Post.arel_table, Post.predicate_builder)
+ relation = relation.merge where: {name: :lol}, readonly: true
- assert_equal Relation::WhereClause.new([:lol], []), relation.where_clause
+ assert_equal({"name"=>:lol}, relation.where_clause.to_h)
assert_equal true, relation.readonly_value
end
@@ -185,7 +182,7 @@ module ActiveRecord
end
test '#values returns a dup of the values' do
- relation = Relation.new(FakeKlass, :b, nil).where! :foo
+ relation = Relation.new(Post, Post.arel_table, Post.predicate_builder).where!(name: :foo)
values = relation.values
values[:where] = nil
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index feb1c29656..2a2c2bc8d0 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -215,7 +215,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_schema_dump_includes_length_for_mysql_blob_and_text_fields
output = standard_dump
- assert_match %r{t\.binary\s+"tiny_blob",\s+limit: 255$}, output
+ assert_match %r{t\.blob\s+"tiny_blob",\s+limit: 255$}, output
assert_match %r{t\.binary\s+"normal_blob",\s+limit: 65535$}, output
assert_match %r{t\.binary\s+"medium_blob",\s+limit: 16777215$}, output
assert_match %r{t\.binary\s+"long_blob",\s+limit: 4294967295$}, output
diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb
index c3fd0b2383..c31f94b2f2 100644
--- a/activerecord/test/cases/tasks/postgresql_rake_test.rb
+++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb
@@ -60,7 +60,7 @@ module ActiveRecord
$stderr.expects(:puts).
with("Couldn't create database for #{@configuration.inspect}")
- ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration }
end
def test_create_when_database_exists_outputs_info_to_stderr
diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb
index 750d5e42dc..0aea0c3b38 100644
--- a/activerecord/test/cases/tasks/sqlite_rake_test.rb
+++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb
@@ -53,7 +53,7 @@ module ActiveRecord
$stderr.expects(:puts).
with("Couldn't create database for #{@configuration.inspect}")
- ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' }
end
end
diff --git a/activerecord/test/fixtures/content.yml b/activerecord/test/fixtures/content.yml
new file mode 100644
index 0000000000..0d12ee03dc
--- /dev/null
+++ b/activerecord/test/fixtures/content.yml
@@ -0,0 +1,3 @@
+content:
+ id: 1
+ title: How to use Rails
diff --git a/activerecord/test/fixtures/content_positions.yml b/activerecord/test/fixtures/content_positions.yml
new file mode 100644
index 0000000000..9e85773f8e
--- /dev/null
+++ b/activerecord/test/fixtures/content_positions.yml
@@ -0,0 +1,3 @@
+content_positions:
+ id: 1
+ content_id: 1
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index a96b8ef0f2..1dcd9fc21e 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -10,7 +10,6 @@ class Company < AbstractCompany
has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account"
has_many :contracts
has_many :developers, :through => :contracts
- has_many :accounts
scope :of_first_firm, lambda {
joins(:account => :firm).
diff --git a/activerecord/test/models/content.rb b/activerecord/test/models/content.rb
new file mode 100644
index 0000000000..140e1dfc78
--- /dev/null
+++ b/activerecord/test/models/content.rb
@@ -0,0 +1,40 @@
+class Content < ActiveRecord::Base
+ self.table_name = 'content'
+ has_one :content_position, dependent: :destroy
+
+ def self.destroyed_ids
+ @destroyed_ids ||= []
+ end
+
+ before_destroy do |object|
+ Content.destroyed_ids << object.id
+ end
+end
+
+class ContentWhichRequiresTwoDestroyCalls < ActiveRecord::Base
+ self.table_name = 'content'
+ has_one :content_position, foreign_key: 'content_id', dependent: :destroy
+
+ after_initialize do
+ @destroy_count = 0
+ end
+
+ before_destroy do
+ @destroy_count += 1
+ if @destroy_count == 1
+ throw :abort
+ end
+ end
+end
+
+class ContentPosition < ActiveRecord::Base
+ belongs_to :content, dependent: :destroy
+
+ def self.destroyed_ids
+ @destroyed_ids ||= []
+ end
+
+ before_destroy do |object|
+ ContentPosition.destroyed_ids << object.id
+ end
+end
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index 7c5941b1af..9a907273f8 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -15,6 +15,8 @@ class Developer < ActiveRecord::Base
end
end
+ belongs_to :mentor
+
accepts_nested_attributes_for :projects
has_and_belongs_to_many :shared_computers, class_name: "Computer"
diff --git a/activerecord/test/models/guitar.rb b/activerecord/test/models/guitar.rb
new file mode 100644
index 0000000000..cd068ff53d
--- /dev/null
+++ b/activerecord/test/models/guitar.rb
@@ -0,0 +1,4 @@
+class Guitar < ActiveRecord::Base
+ has_many :tuning_pegs, index_errors: true
+ accepts_nested_attributes_for :tuning_pegs
+end
diff --git a/activerecord/test/models/mentor.rb b/activerecord/test/models/mentor.rb
new file mode 100644
index 0000000000..11f1e4bff8
--- /dev/null
+++ b/activerecord/test/models/mentor.rb
@@ -0,0 +1,3 @@
+class Mentor < ActiveRecord::Base
+ has_many :developers
+end \ No newline at end of file
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 5328330653..b034e0e267 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -1,4 +1,5 @@
class Project < ActiveRecord::Base
+ belongs_to :mentor
has_and_belongs_to_many :developers, -> { distinct.order 'developers.name desc, developers.id desc' }
has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer"
has_and_belongs_to_many :non_unique_developers, -> { order 'developers.name desc, developers.id desc' }, :class_name => 'Developer'
diff --git a/activerecord/test/models/tuning_peg.rb b/activerecord/test/models/tuning_peg.rb
new file mode 100644
index 0000000000..1252d6dc1d
--- /dev/null
+++ b/activerecord/test/models/tuning_peg.rb
@@ -0,0 +1,4 @@
+class TuningPeg < ActiveRecord::Base
+ belongs_to :guitar
+ validates_numericality_of :pitch
+end
diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb
index 52d3290c84..92e0b197a7 100644
--- a/activerecord/test/schema/mysql2_specific_schema.rb
+++ b/activerecord/test/schema/mysql2_specific_schema.rb
@@ -2,7 +2,7 @@ ActiveRecord::Schema.define do
create_table :binary_fields, force: true do |t|
t.binary :var_binary, limit: 255
t.binary :var_binary_large, limit: 4095
- t.column :tiny_blob, 'tinyblob', limit: 255
+ t.blob :tiny_blob, limit: 255
t.binary :normal_blob, limit: 65535
t.binary :medium_blob, limit: 16777215
t.binary :long_blob, limit: 2147483647
@@ -40,6 +40,17 @@ BEGIN
END
SQL
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP PROCEDURE IF EXISTS topics;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER
+BEGIN
+ select * from topics limit num;
+END
+SQL
+
ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true
ActiveRecord::Base.connection.execute <<-SQL
diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb
index 90f5a60d7b..553cb56103 100644
--- a/activerecord/test/schema/mysql_specific_schema.rb
+++ b/activerecord/test/schema/mysql_specific_schema.rb
@@ -2,7 +2,7 @@ ActiveRecord::Schema.define do
create_table :binary_fields, force: true do |t|
t.binary :var_binary, limit: 255
t.binary :var_binary_large, limit: 4095
- t.column :tiny_blob, 'tinyblob', limit: 255
+ t.blob :tiny_blob, limit: 255
t.binary :normal_blob, limit: 65535
t.binary :medium_blob, limit: 16777215
t.binary :long_blob, limit: 2147483647
@@ -45,9 +45,9 @@ DROP PROCEDURE IF EXISTS topics;
SQL
ActiveRecord::Base.connection.execute <<-SQL
-CREATE PROCEDURE topics() SQL SECURITY INVOKER
+CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER
BEGIN
- select * from topics limit 1;
+ select * from topics limit num;
END
SQL
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index d334a2740e..66a1f5aa8a 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -207,6 +207,14 @@ ActiveRecord::Schema.define do
add_index :companies, [:firm_id, :type], name: "company_partial_index", where: "rating > 10"
add_index :companies, :name, name: 'company_name_index', using: :btree
+ create_table :content, force: true do |t|
+ t.string :title
+ end
+
+ create_table :content_positions, force: true do |t|
+ t.integer :content_id
+ end
+
create_table :vegetables, force: true do |t|
t.string :name
t.integer :seller_id
@@ -253,6 +261,7 @@ ActiveRecord::Schema.define do
t.string :first_name
t.integer :salary, default: 70000
t.integer :firm_id
+ t.integer :mentor_id
if subsecond_precision_supported?
t.datetime :created_at, precision: 6
t.datetime :updated_at, precision: 6
@@ -347,6 +356,10 @@ ActiveRecord::Schema.define do
t.column :key, :string
end
+ create_table :guitar, force: true do |t|
+ t.string :color
+ end
+
create_table :inept_wizards, force: true do |t|
t.column :name, :string, null: false
t.column :city, :string, null: false
@@ -452,6 +465,10 @@ ActiveRecord::Schema.define do
t.string :name
end
+ create_table :mentors, force: true do |t|
+ t.string :name
+ end
+
create_table :minivans, force: true, id: false do |t|
t.string :minivan_id
t.string :name
@@ -660,6 +677,7 @@ ActiveRecord::Schema.define do
t.string :name
t.string :type
t.integer :firm_id
+ t.integer :mentor_id
end
create_table :randomly_named_table1, force: true do |t|
@@ -845,6 +863,11 @@ ActiveRecord::Schema.define do
t.belongs_to :ship
end
+ create_table :tuning_pegs, force: true do |t|
+ t.integer :guitar_id
+ t.float :pitch
+ end
+
create_table :tyres, force: true do |t|
t.integer :car_id
end
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 92efd96de4..3705fc57fc 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,38 @@
+* Change Integer#year to return a Fixnum instead of a Float to improve
+ consistency.
+
+ Integer#years returned a Float while the rest of the accompanying methods
+ (days, weeks, months, etc.) return a Fixnum.
+
+ Before:
+
+ 1.year # => 31557600.0
+
+ After:
+
+ 1.year # => 31557600
+
+ *Konstantinos Rousis*
+
+* Handle invalid UTF-8 strings when HTML escaping
+
+ Use `ActiveSupport::Multibyte::Unicode.tidy_bytes` to handle invalid UTF-8
+ strings in `ERB::Util.unwrapped_html_escape` and `ERB::Util.html_escape_once`.
+ Prevents user-entered input passed from a querystring into a form field from
+ causing invalid byte sequence errors.
+
+ *Grey Baker*
+
+* Update `ActiveSupport::Multibyte::Chars#slice!` to return `nil` if the
+ arguments are out of bounds, to mirror the behavior of `String#slice!`
+
+ *Gourav Tiwari*
+
+* Fix `number_to_human` so that 999999999 rounds to "1 Billion" instead of
+ "1000 Million".
+
+ *Max Jacobson*
+
* Fix `ActiveSupport::Deprecation#deprecate_methods` to report using the
current deprecator instance, where applicable.
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index e6a8b84214..b7da30123a 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -119,11 +119,12 @@ module ActiveSupport
# Translate a key into a file path.
def key_file_path(key)
- if key.size > FILEPATH_MAX_SIZE
- key = Digest::MD5.hexdigest(key)
+ fname = URI.encode_www_form_component(key)
+
+ if fname.size > FILEPATH_MAX_SIZE
+ fname = Digest::MD5.hexdigest(key)
end
- fname = URI.encode_www_form_component(key)
hash = Zlib.adler32(fname)
hash, dir_1 = hash.divmod(0x1000)
dir_2 = hash.modulo(0x1000)
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 252374e817..d43fde03a9 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -748,15 +748,15 @@ module ActiveSupport
protected
- def get_callbacks(name)
+ def get_callbacks(name) # :nodoc:
send "_#{name}_callbacks"
end
- def set_callbacks(name, callbacks)
+ def set_callbacks(name, callbacks) # :nodoc:
send "_#{name}_callbacks=", callbacks
end
- def deprecated_false_terminator
+ def deprecated_false_terminator # :nodoc:
Proc.new do |target, result_lambda|
terminate = true
catch(:abort) do
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
index 234283e792..22fc7ecf92 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -1,15 +1,14 @@
require 'bigdecimal'
require 'bigdecimal/util'
-class BigDecimal
- DEFAULT_STRING_FORMAT = 'F'
- alias_method :to_default_s, :to_s
+module ActiveSupport
+ module BigDecimalWithDefaultFormat #:nodoc:
+ DEFAULT_STRING_FORMAT = 'F'
- def to_s(format = nil, options = nil)
- if format.is_a?(Symbol)
- to_formatted_s(format, options || {})
- else
- to_default_s(format || DEFAULT_STRING_FORMAT)
+ def to_s(format = nil)
+ super(format || DEFAULT_STRING_FORMAT)
end
end
end
+
+BigDecimal.prepend(ActiveSupport::BigDecimalWithDefaultFormat)
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb
index f2b7bb3ef1..802d988af2 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -75,11 +75,15 @@ class Class
instance_predicate = options.fetch(:instance_predicate, true)
attrs.each do |name|
+ remove_possible_singleton_method(name)
define_singleton_method(name) { nil }
+
+ remove_possible_singleton_method("#{name}?")
define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
ivar = "@#{name}"
+ remove_possible_singleton_method("#{name}=")
define_singleton_method("#{name}=") do |val|
singleton_class.class_eval do
remove_possible_method(name)
@@ -110,10 +114,15 @@ class Class
self.class.public_send name
end
end
+
+ remove_possible_method "#{name}?"
define_method("#{name}?") { !!public_send(name) } if instance_predicate
end
- attr_writer name if instance_writer
+ if instance_writer
+ remove_possible_method "#{name}="
+ attr_writer name
+ end
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/integer/time.rb b/activesupport/lib/active_support/core_ext/integer/time.rb
index f0b7382ef3..87185b024f 100644
--- a/activesupport/lib/active_support/core_ext/integer/time.rb
+++ b/activesupport/lib/active_support/core_ext/integer/time.rb
@@ -23,7 +23,7 @@ class Integer
alias :month :months
def years
- ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
+ ActiveSupport::Duration.new(self * 365.25.days.to_i, [[:years, self]])
end
alias :year :years
end
diff --git a/activesupport/lib/active_support/core_ext/module/anonymous.rb b/activesupport/lib/active_support/core_ext/module/anonymous.rb
index 0ecc67a855..510c9a5430 100644
--- a/activesupport/lib/active_support/core_ext/module/anonymous.rb
+++ b/activesupport/lib/active_support/core_ext/module/anonymous.rb
@@ -7,7 +7,7 @@ class Module
# m = Module.new
# m.name # => nil
#
- # +anonymous?+ method returns true if module does not have a name:
+ # +anonymous?+ method returns true if module does not have a name, false otherwise:
#
# Module.new.anonymous? # => true
#
@@ -18,8 +18,10 @@ class Module
# via the +module+ or +class+ keyword or by an explicit assignment:
#
# m = Module.new # creates an anonymous module
- # M = m # => m gets a name here as a side-effect
+ # m.anonymous? # => true
+ # M = m # m gets a name here as a side-effect
# m.name # => "M"
+ # m.anonymous? # => false
def anonymous?
name.nil?
end
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 9dc0dee1bd..0d46248582 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -5,10 +5,11 @@ class Module
# option is not used.
class DelegationError < NoMethodError; end
- RUBY_RESERVED_WORDS = Set.new(
- %w(alias and BEGIN begin break case class def defined? do else elsif END
- end ensure false for if in module next nil not or redo rescue retry
- return self super then true undef unless until when while yield)
+ DELEGATION_RESERVED_METHOD_NAMES = Set.new(
+ %w(_ arg args alias and BEGIN begin block break case class def defined? do
+ else elsif END end ensure false for if in module next nil not or redo
+ rescue retry return self super then true undef unless until when while
+ yield)
).freeze
# Provides a +delegate+ class method to easily expose contained objects'
@@ -171,7 +172,7 @@ class Module
line = line.to_i
to = to.to_s
- to = "self.#{to}" if RUBY_RESERVED_WORDS.include?(to)
+ to = "self.#{to}" if DELEGATION_RESERVED_METHOD_NAMES.include?(to)
methods.each do |method|
# Attribute writer methods only accept one argument. Makes sure []=
diff --git a/activesupport/lib/active_support/core_ext/module/remove_method.rb b/activesupport/lib/active_support/core_ext/module/remove_method.rb
index 52632d2c6b..d5ec16d68a 100644
--- a/activesupport/lib/active_support/core_ext/module/remove_method.rb
+++ b/activesupport/lib/active_support/core_ext/module/remove_method.rb
@@ -6,10 +6,30 @@ class Module
end
end
+ # Removes the named singleton method, if it exists.
+ def remove_possible_singleton_method(method)
+ singleton_class.instance_eval do
+ remove_possible_method(method)
+ end
+ end
+
# Replaces the existing method definition, if there is one, with the passed
# block as its body.
def redefine_method(method, &block)
+ visibility = method_visibility(method)
remove_possible_method(method)
define_method(method, &block)
+ send(visibility, method)
+ end
+
+ def method_visibility(method) # :nodoc:
+ case
+ when private_method_defined?(method)
+ :private
+ when protected_method_defined?(method)
+ :protected
+ else
+ :public
+ end
end
end
diff --git a/activesupport/lib/active_support/core_ext/numeric/conversions.rb b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
index d5bb11deed..9a3651f29a 100644
--- a/activesupport/lib/active_support/core_ext/numeric/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
@@ -1,7 +1,7 @@
require 'active_support/core_ext/big_decimal/conversions'
require 'active_support/number_helper'
-class Numeric
+module ActiveSupport::NumericWithFormat
# Provides options for converting numbers into formatted strings.
# Options are provided for phone numbers, currency, percentage,
@@ -97,7 +97,10 @@ class Numeric
# 1234567.to_s(:human, precision: 1,
# separator: ',',
# significant: false) # => "1,2 Million"
- def to_formatted_s(format = :default, options = {})
+ def to_s(*args)
+ format, options = args
+ options ||= {}
+
case format
when :phone
return ActiveSupport::NumberHelper.number_to_phone(self, options)
@@ -114,32 +117,16 @@ class Numeric
when :human_size
return ActiveSupport::NumberHelper.number_to_human_size(self, options)
else
- self.to_default_s
- end
- end
-
- [Fixnum, Bignum].each do |klass|
- klass.class_eval do
- alias_method :to_default_s, :to_s
- def to_s(base_or_format = 10, options = nil)
- if base_or_format.is_a?(Symbol)
- to_formatted_s(base_or_format, options || {})
- else
- to_default_s(base_or_format)
- end
- end
+ super
end
end
- Float.class_eval do
- alias_method :to_default_s, :to_s
- def to_s(*args)
- if args.empty?
- to_default_s
- else
- to_formatted_s(*args)
- end
- end
+ def to_formatted_s(*args)
+ to_s(*args)
end
+ deprecate to_formatted_s: :to_s
+end
+[Fixnum, Bignum, Float, BigDecimal].each do |klass|
+ klass.prepend(ActiveSupport::NumericWithFormat)
end
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb
index 8b27ec4413..510fa48189 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -37,7 +37,7 @@ class ERB
if s.html_safe?
s
else
- s.gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
+ ActiveSupport::Multibyte::Unicode.tidy_bytes(s).gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
end
end
module_function :unwrapped_html_escape
@@ -50,7 +50,7 @@ class ERB
# html_escape_once('&lt;&lt; Accept & Checkout')
# # => "&lt;&lt; Accept &amp; Checkout"
def html_escape_once(s)
- result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
+ result = ActiveSupport::Multibyte::Unicode.tidy_bytes(s.to_s).gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
s.html_safe? ? result.html_safe : result
end
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index eecbac2c20..536c4bf525 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -6,6 +6,7 @@ class Time
:db => '%Y-%m-%d %H:%M:%S',
:number => '%Y%m%d%H%M%S',
:nsec => '%Y%m%d%H%M%S%9N',
+ :usec => '%Y%m%d%H%M%S%6N',
:time => '%H:%M',
:short => '%d %b %H:%M',
:long => '%B %d, %Y %H:%M',
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index f6a2e7e949..707cf200b5 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -86,7 +86,8 @@ module ActiveSupport #:nodoc:
end
# Works like <tt>String#slice!</tt>, but returns an instance of
- # Chars, or nil if the string was not modified.
+ # Chars, or nil if the string was not modified. The string will not be
+ # modified if the range given is out of bounds
#
# string = 'Welcome'
# string.mb_chars.slice!(3) # => #<ActiveSupport::Multibyte::Chars:0x000000038109b8 @wrapped_string="c">
@@ -94,7 +95,10 @@ module ActiveSupport #:nodoc:
# string.mb_chars.slice!(0..3) # => #<ActiveSupport::Multibyte::Chars:0x00000002eb80a0 @wrapped_string="Welo">
# string # => 'me'
def slice!(*args)
- chars(@wrapped_string.slice!(*args))
+ string_sliced = @wrapped_string.slice!(*args)
+ if string_sliced
+ chars(string_sliced)
+ end
end
# Reverses all characters in the string.
diff --git a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
index 5c6fe2df83..7a1f8171c0 100644
--- a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
@@ -20,9 +20,11 @@ module ActiveSupport
exponent = calculate_exponent(units)
@number = number / (10 ** exponent)
+ until (rounded_number = NumberToRoundedConverter.convert(number, options)) != NumberToRoundedConverter.convert(1000, options)
+ @number = number / 1000.0
+ exponent += 3
+ end
unit = determine_unit(units, exponent)
-
- rounded_number = NumberToRoundedConverter.convert(number, options)
format.gsub('%n'.freeze, rounded_number).gsub('%u'.freeze, unit).strip
end
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 681f659100..9f4bb6762d 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -26,12 +26,6 @@ module ActiveSupport
# Time.zone # => #<ActiveSupport::TimeZone:0x514834...>
# Time.zone.name # => "Eastern Time (US & Canada)"
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
- #
- # The version of TZInfo bundled with Active Support only includes the
- # definitions necessary to support the zones defined by the TimeZone class.
- # If you need to use zones that aren't defined by TimeZone, you'll need to
- # install the TZInfo gem (if a recent version of the gem is installed locally,
- # this will be used instead of the bundled version.)
class TimeZone
# Keys are Rails TimeZone names, values are TZInfo identifiers.
MAPPING = {
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index c235dee5e1..fb52613a23 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -762,6 +762,11 @@ class FileStoreTest < ActiveSupport::TestCase
assert_equal 1, @cache.read("a"*10000)
end
+ def test_long_uri_encoded_keys
+ @cache.write("%"*870, 1)
+ assert_equal 1, @cache.read("%"*870)
+ end
+
def test_key_transformation
key = @cache.send(:key_file_path, "views/index?id=1")
assert_equal "views/index?id=1", @cache.send(:file_path_key, key)
diff --git a/activesupport/test/core_ext/module/remove_method_test.rb b/activesupport/test/core_ext/module/remove_method_test.rb
index 4657f0c175..0d684dc70e 100644
--- a/activesupport/test/core_ext/module/remove_method_test.rb
+++ b/activesupport/test/core_ext/module/remove_method_test.rb
@@ -6,24 +6,54 @@ module RemoveMethodTests
def do_something
return 1
end
-
+
+ def do_something_protected
+ return 1
+ end
+ protected :do_something_protected
+
+ def do_something_private
+ return 1
+ end
+ private :do_something_private
+
+ class << self
+ def do_something_else
+ return 2
+ end
+ end
end
end
class RemoveMethodTest < ActiveSupport::TestCase
-
+
def test_remove_method_from_an_object
RemoveMethodTests::A.class_eval{
self.remove_possible_method(:do_something)
}
assert !RemoveMethodTests::A.new.respond_to?(:do_something)
end
-
+
+ def test_remove_singleton_method_from_an_object
+ RemoveMethodTests::A.class_eval{
+ self.remove_possible_singleton_method(:do_something_else)
+ }
+ assert !RemoveMethodTests::A.respond_to?(:do_something_else)
+ end
+
def test_redefine_method_in_an_object
RemoveMethodTests::A.class_eval{
self.redefine_method(:do_something) { return 100 }
+ self.redefine_method(:do_something_protected) { return 100 }
+ self.redefine_method(:do_something_private) { return 100 }
}
assert_equal 100, RemoveMethodTests::A.new.do_something
+ assert_equal 100, RemoveMethodTests::A.new.send(:do_something_protected)
+ assert_equal 100, RemoveMethodTests::A.new.send(:do_something_private)
+
+ assert RemoveMethodTests::A.public_method_defined? :do_something
+ assert RemoveMethodTests::A.protected_method_defined? :do_something_protected
+ assert RemoveMethodTests::A.private_method_defined? :do_something_private
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index bdfbadcf1d..0ed66f8c37 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -83,6 +83,16 @@ Product = Struct.new(:name) do
end
end
+class Block
+ def hello?
+ true
+ end
+end
+
+HasBlock = Struct.new(:block) do
+ delegate :hello?, to: :block
+end
+
class ParameterSet
delegate :[], :[]=, :to => :@params
@@ -301,6 +311,11 @@ class ModuleTest < ActiveSupport::TestCase
assert_raise(NoMethodError) { product.type_name }
end
+ def test_delegation_with_method_arguments
+ has_block = HasBlock.new(Block.new)
+ assert has_block.hello?
+ end
+
def test_parent
assert_equal Yz::Zy, Yz::Zy::Cd.parent
assert_equal Yz, Yz::Zy.parent
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index 3a5d6df06d..9cc7bb1a77 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -782,8 +782,8 @@ class OutputSafetyTest < ActiveSupport::TestCase
end
test "ERB::Util.html_escape should correctly handle invalid UTF-8 strings" do
- string = [192, 60].pack('CC')
- expected = 192.chr + "&lt;"
+ string = "\251 <"
+ expected = "© &lt;"
assert_equal expected, ERB::Util.html_escape(string)
end
@@ -799,6 +799,12 @@ class OutputSafetyTest < ActiveSupport::TestCase
assert_equal escaped_string, ERB::Util.html_escape_once(string)
assert_equal escaped_string, ERB::Util.html_escape_once(escaped_string)
end
+
+ test "ERB::Util.html_escape_once should correctly handle invalid UTF-8 strings" do
+ string = "\251 <"
+ expected = "© &lt;"
+ assert_equal expected, ERB::Util.html_escape_once(string)
+ end
end
class StringExcludeTest < ActiveSupport::TestCase
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index b14c04fba6..2d0fb70a6b 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -534,6 +534,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal "17:44", time.to_s(:time)
assert_equal "20050221174430", time.to_s(:number)
assert_equal "20050221174430123456789", time.to_s(:nsec)
+ assert_equal "20050221174430123456", time.to_s(:usec)
assert_equal "February 21, 2005 17:44", time.to_s(:long)
assert_equal "February 21st, 2005 17:44", time.to_s(:long_ordinal)
with_env_tz "UTC" do
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
index e1c4b705f8..8d4d9d736c 100644
--- a/activesupport/test/multibyte_chars_test.rb
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -413,12 +413,24 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
assert_equal 'にち', @chars.slice!(1..2)
end
+ def test_slice_bang_returns_nil_on_out_of_bound_arguments
+ assert_equal nil, @chars.mb_chars.slice!(9..10)
+ end
+
def test_slice_bang_removes_the_slice_from_the_receiver
chars = 'úüù'.mb_chars
chars.slice!(0,2)
assert_equal 'ù', chars
end
+ def test_slice_bang_returns_nil_and_does_not_modify_receiver_if_out_of_bounds
+ string = 'úüù'
+ chars = string.mb_chars
+ assert_nil chars.slice!(4, 5)
+ assert_equal 'úüù', chars
+ assert_equal 'úüù', string
+ end
+
def test_slice_should_throw_exceptions_on_invalid_arguments
assert_raise(TypeError) { @chars.slice(2..3, 1) }
assert_raise(TypeError) { @chars.slice(1, 2..3) }
diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb
index 944bce1b41..7f62d7c0b3 100644
--- a/activesupport/test/number_helper_test.rb
+++ b/activesupport/test/number_helper_test.rb
@@ -296,6 +296,8 @@ module ActiveSupport
assert_equal '1.2346 Million', number_helper.number_to_human(1234567, :precision => 4, :significant => false)
assert_equal '1,2 Million', number_helper.number_to_human(1234567, :precision => 1, :significant => false, :separator => ',')
assert_equal '1 Million', number_helper.number_to_human(1234567, :precision => 0, :significant => true, :separator => ',') #significant forced to false
+ assert_equal '1 Million', number_helper.number_to_human(999999)
+ assert_equal '1 Billion', number_helper.number_to_human(999999999)
end
end
diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb
index 03a63e94e8..917fa46c96 100644
--- a/activesupport/test/tagged_logging_test.rb
+++ b/activesupport/test/tagged_logging_test.rb
@@ -72,11 +72,11 @@ class TaggedLoggingTest < ActiveSupport::TestCase
test "keeps each tag in their own thread" do
@logger.tagged("BCX") do
Thread.new do
- @logger.tagged("OMG") { @logger.info "Cool story bro" }
+ @logger.tagged("OMG") { @logger.info "Cool story" }
end.join
@logger.info "Funky time"
end
- assert_equal "[OMG] Cool story bro\n[BCX] Funky time\n", @output.string
+ assert_equal "[OMG] Cool story\n[BCX] Funky time\n", @output.string
end
test "keeps each tag in their own instance" do
@@ -84,11 +84,11 @@ class TaggedLoggingTest < ActiveSupport::TestCase
@other_logger = ActiveSupport::TaggedLogging.new(MyLogger.new(@other_output))
@logger.tagged("OMG") do
@other_logger.tagged("BCX") do
- @logger.info "Cool story bro"
+ @logger.info "Cool story"
@other_logger.info "Funky time"
end
end
- assert_equal "[OMG] Cool story bro\n", @output.string
+ assert_equal "[OMG] Cool story\n", @output.string
assert_equal "[BCX] Funky time\n", @other_output.string
end
@@ -97,11 +97,11 @@ class TaggedLoggingTest < ActiveSupport::TestCase
Thread.new do
@logger.tagged("OMG") do
@logger.flush
- @logger.info "Cool story bro"
+ @logger.info "Cool story"
end
end.join
end
- assert_equal "[FLUSHED]\nCool story bro\n", @output.string
+ assert_equal "[FLUSHED]\nCool story\n", @output.string
end
test "mixed levels of tagging" do
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 7f88c13dc0..dd4d9f55fa 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -149,8 +149,10 @@ false` as an argument. This technique should be used with caution.
### `valid?` and `invalid?`
-To verify whether or not an object is valid, Rails uses the `valid?` method.
-You can also use this method on your own. `valid?` triggers your validations
+Before saving an ActiveRecord object, Rails runs your validations.
+If these validations produce any errors, Rails does not save the object.
+
+You can also run these validations on your own. `valid?` triggers your validations
and returns true if no errors were found in the object, and false otherwise.
As you saw above:
@@ -168,8 +170,9 @@ through the `errors.messages` instance method, which returns a collection of err
By definition, an object is valid if this collection is empty after running
validations.
-Note that an object instantiated with `new` will not report errors even if it's
-technically invalid, because validations are not run when using `new`.
+Note that an object instantiated with `new` will not report errors
+even if it's technically invalid, because validations are automatically run
+only when the object is saved, such as with the `create` or `save` methods.
```ruby
class Person < ActiveRecord::Base
@@ -986,6 +989,10 @@ class method, passing in the symbols for the validation methods' names.
You can pass more than one symbol for each class method and the respective
validations will be run in the same order as they were registered.
+The `valid?` method will verify that the errors collection is empty,
+so your custom validation methods should add errors to it when you
+wish validation to fail:
+
```ruby
class Invoice < ActiveRecord::Base
validate :expiration_date_cannot_be_in_the_past,
@@ -1005,9 +1012,10 @@ class Invoice < ActiveRecord::Base
end
```
-By default such validations will run every time you call `valid?`. It is also
-possible to control when to run these custom validations by giving an `:on`
-option to the `validate` method, with either: `:create` or `:update`.
+By default, such validations will run every time you call `valid?`
+or save the object. But it is also possible to control when to run these
+custom validations by giving an `:on` option to the `validate` method,
+with either: `:create` or `:update`.
```ruby
class Invoice < ActiveRecord::Base
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 5a68f6c869..556b5ede3c 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -453,7 +453,7 @@ NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
#### `instance_variable_names`
-The method `instance_variable_names` returns an array. Each name includes the "@" sign.
+The method `instance_variable_names` returns an array. Each name includes the "@" sign.
```ruby
class C
@@ -2073,30 +2073,22 @@ Extensions to `BigDecimal`
--------------------------
### `to_s`
-The method `to_s` is aliased to `to_formatted_s`. This provides a convenient way to display a BigDecimal value in floating-point notation:
+The method `to_s` provides a default specifier of "F". This means that a simple call to `to_s` will result in floating point representation instead of engineering notation:
```ruby
BigDecimal.new(5.00, 6).to_s # => "5.0"
```
-### `to_formatted_s`
-
-Te method `to_formatted_s` provides a default specifier of "F". This means that a simple call to `to_formatted_s` or `to_s` will result in floating point representation instead of engineering notation:
-
-```ruby
-BigDecimal.new(5.00, 6).to_formatted_s # => "5.0"
-```
-
and that symbol specifiers are also supported:
```ruby
-BigDecimal.new(5.00, 6).to_formatted_s(:db) # => "5.0"
+BigDecimal.new(5.00, 6).to_s(:db) # => "5.0"
```
Engineering notation is still supported:
```ruby
-BigDecimal.new(5.00, 6).to_formatted_s("e") # => "0.5E1"
+BigDecimal.new(5.00, 6).to_s("e") # => "0.5E1"
```
Extensions to `Enumerable`
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index e5a560edd0..f495acbf68 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -232,6 +232,7 @@ Active Record
| `:sql` | SQL statement |
| `:name` | Name of the operation |
| `:connection_id` | `self.object_id` |
+| `:binds` | Bind parameters |
INFO. The adapters will add their own data as well.
diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md
index 526bf768cc..73e62eb6d9 100644
--- a/guides/source/api_documentation_guidelines.md
+++ b/guides/source/api_documentation_guidelines.md
@@ -84,10 +84,11 @@ English
Please use American English (*color*, *center*, *modularize*, etc). See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
-Comma
--------
+Oxford Comma
+------------
-Please use the Oxford comma (*red, white, and blue* style). See [the detail of Oxford comma](http://en.wikipedia.org/wiki/Serial_comma).
+Please use the [Oxford comma](http://en.wikipedia.org/wiki/Serial_comma)
+("red, white, and blue", instead of "red, white and blue").
Example Code
------------
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index 7b8d2d3aef..41881abb62 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -662,7 +662,7 @@ generates something like this:
rel="stylesheet" />
```
-Note: with the Asset Pipeline the :cache and :concat options aren't used
+NOTE: with the Asset Pipeline the `:cache` and `:concat` options aren't used
anymore, delete these options from the `javascript_include_tag` and
`stylesheet_link_tag`.
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 87114c4ef0..e2125cae2e 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -304,13 +304,19 @@ All these configuration options are delegated to the `I18n` library.
`:all` which always dumps all schemas regardless of the schema_search_path,
or a string of comma separated schemas.
-* `config.active_record.belongs_to_required_by_default` is a boolean value and controls whether `belongs_to` association is required by default.
+* `config.active_record.belongs_to_required_by_default` is a boolean value and
+ controls whether a record fails validation if `belongs_to` association is not
+ present.
* `config.active_record.warn_on_records_fetched_greater_than` allows setting a
warning threshold for query result size. If the number of records returned
by a query exceeds the threshold, a warning is logged. This can be used to
identify queries which might be causing memory bloat.
+* `config.active_record.index_nested_attribute_errors` allows errors for nested
+ has_many relationships to be displayed with an index as well as the error.
+ Defaults to false.
+
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/engines.md b/guides/source/engines.md
index 71844b7990..f961b799f1 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -670,7 +670,7 @@ pre-defined path which may be customizable.
The engine contains migrations for the `blorgh_articles` and `blorgh_comments`
table which need to be created in the application's database so that the
engine's models can query them correctly. To copy these migrations into the
-application use this command:
+application run the following command from the `test/dummy` directory of your Rails engine:
```bash
$ rake blorgh:install:migrations
diff --git a/guides/source/initialization.md b/guides/source/initialization.md
index 43083ebb86..ebe1cb206a 100644
--- a/guides/source/initialization.md
+++ b/guides/source/initialization.md
@@ -86,10 +86,9 @@ The `APP_PATH` constant will be used later in `rails/commands`. The `config/boot
`config/boot.rb` contains:
```ruby
-# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
-require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
+require 'bundler/setup' # Set up gems listed in the Gemfile.
```
In a standard Rails application, there's a `Gemfile` which declares all
diff --git a/guides/source/routing.md b/guides/source/routing.md
index 3175716a9c..245689932b 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -79,7 +79,7 @@ it asks the router to map it to a controller action. If the first matching route
resources :photos
```
-Rails would dispatch that request to the `destroy` method on the `photos` controller with `{ id: '17' }` in `params`.
+Rails would dispatch that request to the `destroy` action on the `photos` controller with `{ id: '17' }` in `params`.
### CRUD, Verbs, and Actions
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 7916e24af1..e81ec62a1d 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -167,6 +167,9 @@ module Rails
# team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
@caching_key_generator ||=
if secrets.secret_key_base
+ unless secrets.secret_key_base.kind_of?(String)
+ raise ArgumentError, "`secret_key_base` for #{Rails.env} environment must be a type of String, change this value in `config/secrets.yml`"
+ end
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
ActiveSupport::CachingKeyGenerator.new(key_generator)
else
diff --git a/railties/lib/rails/console/helpers.rb b/railties/lib/rails/console/helpers.rb
index b775f1ff8d..a33f71dc5b 100644
--- a/railties/lib/rails/console/helpers.rb
+++ b/railties/lib/rails/console/helpers.rb
@@ -4,7 +4,7 @@ module Rails
#
# This method assumes an +ApplicationController+ exists, and it extends +ActionController::Base+
def helper
- @helper ||= ApplicationController.helpers
+ ApplicationController.helpers
end
# Gets a new instance of a controller object.
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
index b4ddee3b1b..8cadbc3ddd 100644
--- a/railties/lib/rails/engine/configuration.rb
+++ b/railties/lib/rails/engine/configuration.rb
@@ -26,7 +26,7 @@ module Rails
#
# config.generators.colorize_logging = false
#
- def generators #:nodoc:
+ def generators
@generators ||= Rails::Configuration::Generators.new
yield(@generators) if block_given?
@generators
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index c65b8b84be..eeeef430bb 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -117,7 +117,7 @@ task default: :test
remove_file "Gemfile"
remove_file "lib/tasks"
remove_file "public/robots.txt"
- remove_file "README"
+ remove_file "README.md"
remove_file "test"
remove_file "vendor"
end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index d96d8ded6b..ebcfcb1c3a 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -417,6 +417,19 @@ module ApplicationTests
end
end
+ test "raise when secrets.secret_key_base is not a type of string" do
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base: 123
+ YAML
+
+ app 'development'
+
+ assert_raise(ArgumentError) do
+ app.key_generator
+ end
+ end
+
test "prefer secrets.secret_token over config.secret_token" do
app_file 'config/initializers/secret_token.rb', <<-RUBY
Rails.application.config.secret_token = ""
diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb
index 4906f9a1e8..7b4babb13b 100644
--- a/railties/test/application/middleware/exceptions_test.rb
+++ b/railties/test/application/middleware/exceptions_test.rb
@@ -48,7 +48,7 @@ module ApplicationTests
test "uses custom exceptions app" do
add_to_config <<-RUBY
config.exceptions_app = lambda do |env|
- [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED"]]
end
RUBY
@@ -56,7 +56,7 @@ module ApplicationTests
get "/foo"
assert_equal 404, last_response.status
- assert_equal "YOU FAILED BRO", last_response.body
+ assert_equal "YOU FAILED", last_response.body
end
test "url generation error when action_dispatch.show_exceptions is set raises an exception" do
@@ -67,7 +67,7 @@ module ApplicationTests
end
end
RUBY
-
+
app.config.action_dispatch.show_exceptions = true
get '/foo'
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index e7beab8b5e..f94d08673a 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -49,6 +49,58 @@ module ApplicationTests
db_create_and_drop database_url_db_name
end
+ def with_database_existing
+ Dir.chdir(app_path) do
+ set_database_url
+ `bin/rake db:create`
+ yield
+ `bin/rake db:drop`
+ end
+ end
+
+ test 'db:create failure because database exists' do
+ with_database_existing do
+ output = `bin/rake db:create 2>&1`
+ assert_match /already exists/, output
+ assert_equal 0, $?.exitstatus
+ end
+ end
+
+ def with_bad_permissions
+ Dir.chdir(app_path) do
+ set_database_url
+ FileUtils.chmod("-w", "db")
+ yield
+ FileUtils.chmod("+w", "db")
+ end
+ end
+
+ test 'db:create failure because bad permissions' do
+ with_bad_permissions do
+ output = `bin/rake db:create 2>&1`
+ assert_match /Couldn't create database/, output
+ assert_equal 1, $?.exitstatus
+ end
+ end
+
+ test 'db:drop failure because database does not exist' do
+ Dir.chdir(app_path) do
+ output = `bin/rake db:drop 2>&1`
+ assert_match /does not exist/, output
+ assert_equal 0, $?.exitstatus
+ end
+ end
+
+ test 'db:drop failure because bad permissions' do
+ with_database_existing do
+ with_bad_permissions do
+ output = `bin/rake db:drop 2>&1`
+ assert_match /Couldn't drop/, output
+ assert_equal 1, $?.exitstatus
+ end
+ end
+ end
+
def db_migrate_and_status(expected_database)
Dir.chdir(app_path) do
`bin/rails generate model book title:string;
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 57bc220558..199743a396 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -221,6 +221,15 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_uuid_to_create_table_migration
+ run_generator ["create_books", "--primary_key_type=uuid"]
+ assert_migration "db/migrate/create_books.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/create_table :books, id: :uuid/, change)
+ end
+ end
+ end
+
def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove_or_create
migration = "delete_books"
run_generator [migration, "title:string", "content:text"]
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index abd3ff50a4..64b9a480f3 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -374,6 +374,15 @@ class ModelGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_uuid_to_create_table_migration
+ run_generator ["account", "--primary_key_type=uuid"]
+ assert_migration "db/migrate/create_accounts.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/create_table :accounts, id: :uuid/, change)
+ end
+ end
+ end
+
def test_required_belongs_to_adds_required_association
run_generator ["account", "supplier:references{required}"]
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index a19a29056d..715debf344 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -440,6 +440,19 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_unnecessary_files_are_not_generated_in_dummy_application
+ run_generator
+ assert_no_file 'test/dummy/.gitignore'
+ assert_no_file 'test/dummy/db/seeds.rb'
+ assert_no_file 'test/dummy/Gemfile'
+ assert_no_file 'test/dummy/public/robots.txt'
+ assert_no_file 'test/dummy/README.md'
+ assert_no_directory 'test/dummy/lib/tasks'
+ assert_no_directory 'test/dummy/doc'
+ assert_no_directory 'test/dummy/test'
+ assert_no_directory 'test/dummy/vendor'
+ end
+
def test_skipping_test_files
run_generator [destination_root, "--skip-test"]
assert_no_file "test"