diff options
34 files changed, 251 insertions, 201 deletions
@@ -11,7 +11,7 @@ gem 'rack-cache', '~> 1.2' gem 'jquery-rails', '~> 3.1.0' gem 'turbolinks' gem 'coffee-rails', '~> 4.0.0' -gem 'arel', github: 'rails/arel' +gem 'arel', github: 'rails/arel', branch: 'master' gem 'sprockets-rails', github: 'rails/sprockets-rails', branch: '2-1-stable' # require: false so bcrypt is loaded only when has_secure_password is used. diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index caaebc537a..c6a8f581de 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -550,6 +550,31 @@ module ActionController end end + # Simulate a HTTP request to +action+ by specifying request method, + # parameters and set/volley the response. + # + # - +action+: The controller action to call. + # - +http_method+: Request method used to send the http request. Possible values + # are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+. + # - +parameters+: The HTTP parameters. This may be +nil+, a hash, or a + # string that is appropriately encoded (+application/x-www-form-urlencoded+ + # or +multipart/form-data+). + # - +session+: A hash of parameters to store in the session. This may be +nil+. + # - +flash+: A hash of parameters to store in the flash. This may be +nil+. + # + # Example calling +create+ action and sending two params: + # + # process :create, 'POST', user: { name: 'Gaurish Sharma', email: 'user@example.com' } + # + # Example sending parameters, +nil+ session and setting a flash message: + # + # process :view, 'GET', { id: 7 }, nil, { notice: 'This is flash message' } + # + # To simulate +GET+, +POST+, +PATCH+, +PUT+, +DELETE+ and +HEAD+ requests + # prefer using #get, #post, #patch, #put, #delete and #head methods + # respectively which will make tests more expressive. + # + # Note that the request method is not verified. def process(action, http_method = 'GET', *args) check_required_ivars diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index dd2cbdcddc..b800ee6448 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -104,7 +104,10 @@ module ActionDispatch recipient = self if record_or_hash_or_array.kind_of?(Array) - record_or_hash_or_array = record_or_hash_or_array.compact + if record_or_hash_or_array.include? nil + raise ArgumentError, "Nil location provided. Can't build URI." + end + record_or_hash_or_array = record_or_hash_or_array.dup if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy) recipient = record_or_hash_or_array.shift end diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb index 3655b90e32..00d4612ac9 100644 --- a/actionpack/test/controller/force_ssl_test.rb +++ b/actionpack/test/controller/force_ssl_test.rb @@ -93,8 +93,6 @@ class RedirectToSSL < ForceSSLController end class ForceSSLControllerLevelTest < ActionController::TestCase - tests ForceSSLControllerLevel - def test_banana_redirects_to_https get :banana assert_response 301 @@ -115,8 +113,6 @@ class ForceSSLControllerLevelTest < ActionController::TestCase end class ForceSSLCustomOptionsTest < ActionController::TestCase - tests ForceSSLCustomOptions - def setup @request.env['HTTP_HOST'] = 'www.example.com:80' end @@ -189,8 +185,6 @@ class ForceSSLCustomOptionsTest < ActionController::TestCase end class ForceSSLOnlyActionTest < ActionController::TestCase - tests ForceSSLOnlyAction - def test_banana_not_redirects_to_https get :banana assert_response 200 @@ -204,8 +198,6 @@ class ForceSSLOnlyActionTest < ActionController::TestCase end class ForceSSLExceptActionTest < ActionController::TestCase - tests ForceSSLExceptAction - def test_banana_not_redirects_to_https get :banana assert_response 200 @@ -219,8 +211,6 @@ class ForceSSLExceptActionTest < ActionController::TestCase end class ForceSSLIfConditionTest < ActionController::TestCase - tests ForceSSLIfCondition - def test_banana_not_redirects_to_https get :banana assert_response 200 @@ -234,8 +224,6 @@ class ForceSSLIfConditionTest < ActionController::TestCase end class ForceSSLFlashTest < ActionController::TestCase - tests ForceSSLFlash - def test_cheeseburger_redirects_to_https get :set_flash assert_response 302 @@ -315,7 +303,6 @@ class ForceSSLOptionalSegmentsTest < ActionController::TestCase end class RedirectToSSLTest < ActionController::TestCase - tests RedirectToSSL def test_banana_redirects_to_https_if_not_https get :banana assert_response 301 @@ -334,4 +321,4 @@ class RedirectToSSLTest < ActionController::TestCase assert_response 200 assert_equal 'ihaz', response.body end -end
\ No newline at end of file +end diff --git a/actionpack/test/controller/mime/accept_format_test.rb b/actionpack/test/controller/mime/accept_format_test.rb index c03c7edeb8..811c507af2 100644 --- a/actionpack/test/controller/mime/accept_format_test.rb +++ b/actionpack/test/controller/mime/accept_format_test.rb @@ -9,8 +9,6 @@ class StarStarMimeController < ActionController::Base end class StarStarMimeControllerTest < ActionController::TestCase - tests StarStarMimeController - def test_javascript_with_format @request.accept = "text/javascript" get :index, :format => 'js' diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb index ce6d135d92..41503e11a8 100644 --- a/actionpack/test/controller/mime/respond_to_test.rb +++ b/actionpack/test/controller/mime/respond_to_test.rb @@ -258,8 +258,6 @@ class RespondToController < ActionController::Base end class RespondToControllerTest < ActionController::TestCase - tests RespondToController - def setup super @request.host = "www.example.com" diff --git a/actionpack/test/controller/mime/respond_with_test.rb b/actionpack/test/controller/mime/respond_with_test.rb index a70592fa1b..416b3b81a5 100644 --- a/actionpack/test/controller/mime/respond_with_test.rb +++ b/actionpack/test/controller/mime/respond_with_test.rb @@ -138,8 +138,6 @@ class EmptyRespondWithController < ActionController::Base end class RespondWithControllerTest < ActionController::TestCase - tests RespondWithController - def setup super @request.host = "www.example.com" diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 4df2f8b98d..b0983a5252 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -30,7 +30,6 @@ class SendFileWithActionControllerLive < SendFileController end class SendFileTest < ActionController::TestCase - tests SendFileController include TestFileUtils Mime::Type.register "image/png", :png unless defined? Mime::PNG diff --git a/actionview/lib/action_view/lookup_context.rb b/actionview/lib/action_view/lookup_context.rb index 855fed0190..5fff6b0771 100644 --- a/actionview/lib/action_view/lookup_context.rb +++ b/actionview/lib/action_view/lookup_context.rb @@ -114,7 +114,7 @@ module ActionView module ViewPaths attr_reader :view_paths, :html_fallback_for_js - # Whenever setting view paths, makes a copy so we can manipulate then in + # Whenever setting view paths, makes a copy so that we can manipulate them in # instance objects as we wish. def view_paths=(paths) @view_paths = ActionView::PathSet.new(Array(paths)) @@ -134,7 +134,8 @@ module ActionView end alias :template_exists? :exists? - # Add fallbacks to the view paths. Useful in cases you are rendering a :file. + # Adds fallbacks to the view paths. Useful in cases when you are rendering + # a :file. def with_fallbacks added_resolvers = 0 self.class.fallbacks.each do |resolver| @@ -227,7 +228,7 @@ module ActionView end # Overload locale= to also set the I18n.locale. If the current I18n.config object responds - # to original_config, it means that it's has a copy of the original I18n configuration and it's + # to original_config, it means that it has a copy of the original I18n configuration and it's # acting as proxy, which we need to skip. def locale=(value) if value @@ -238,7 +239,7 @@ module ActionView super(@skip_default_locale ? I18n.locale : default_locale) end - # A method which only uses the first format in the formats array for layout lookup. + # Uses the first format in the formats array for layout lookup. def with_layout_format if formats.size == 1 yield diff --git a/actionview/test/activerecord/polymorphic_routes_test.rb b/actionview/test/activerecord/polymorphic_routes_test.rb index afb714484b..1ead18518a 100644 --- a/actionview/test/activerecord/polymorphic_routes_test.rb +++ b/actionview/test/activerecord/polymorphic_routes_test.rb @@ -112,6 +112,31 @@ class PolymorphicRoutesTest < ActionController::TestCase end end + def test_with_empty_list + with_test_routes do + assert_raise ArgumentError, "Nil location provided. Can't build URI." do + polymorphic_url([]) + end + end + end + + def test_with_nil_id + with_test_routes do + assert_raise ArgumentError, "Nil location provided. Can't build URI." do + polymorphic_url({ :id => nil }) + end + end + end + + def test_with_nil_in_list + with_test_routes do + assert_raise ArgumentError, "Nil location provided. Can't build URI." do + @series.save + polymorphic_url([nil, @series]) + end + end + end + def test_with_record with_test_routes do @project.save @@ -295,17 +320,17 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - def test_nesting_with_array_containing_nil + def test_nesting_with_array with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}/bid", polymorphic_url([@project, nil, :bid]) + assert_equal "http://example.com/projects/#{@project.id}/bid", polymorphic_url([@project, :bid]) end end def test_with_array_containing_single_object with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url([nil, @project]) + assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url([@project]) end end @@ -438,7 +463,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_with_array_containing_single_irregular_plural_object with_test_routes do @tax.save - assert_equal "http://example.com/taxes/#{@tax.id}", polymorphic_url([nil, @tax]) + assert_equal "http://example.com/taxes/#{@tax.id}", polymorphic_url([@tax]) end end diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md index 8f892ea3a7..68cc874ca3 100644 --- a/activemodel/CHANGELOG.md +++ b/activemodel/CHANGELOG.md @@ -1,3 +1,7 @@ +* Add plural and singular form for length validator's default messages + + *Abd ar-Rahman Hamid* + * Introduce `validate` as an alias for `valid?`. This is more intuitive when you want to run validations but don't care about diff --git a/activemodel/lib/active_model/locale/en.yml b/activemodel/lib/active_model/locale/en.yml index 540e8132d3..bf07945fe1 100644 --- a/activemodel/lib/active_model/locale/en.yml +++ b/activemodel/lib/active_model/locale/en.yml @@ -14,9 +14,15 @@ en: empty: "can't be empty" blank: "can't be blank" present: "must be blank" - too_long: "is too long (maximum is %{count} characters)" - too_short: "is too short (minimum is %{count} characters)" - wrong_length: "is the wrong length (should be %{count} characters)" + too_long: + one: "is too long (maximum is 1 character)" + other: "is too long (maximum is %{count} characters)" + too_short: + one: "is too short (minimum is 1 character)" + other: "is too short (minimum is %{count} characters)" + wrong_length: + one: "is the wrong length (should be 1 character)" + other: "is the wrong length (should be %{count} characters)" not_a_number: "is not a number" not_an_integer: "must be an integer" greater_than: "must be greater than %{count}" diff --git a/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb index 93600c587a..3eeb80a48b 100644 --- a/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb +++ b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb @@ -72,28 +72,40 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase end # validates_length_of: generate_message(attr, :too_long, message: custom_message, count: option_value.end) - def test_generate_message_too_long_with_default_message + def test_generate_message_too_long_with_default_message_plural assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, count: 10) end + def test_generate_message_too_long_with_default_message_singular + assert_equal "is too long (maximum is 1 character)", @person.errors.generate_message(:title, :too_long, count: 1) + end + def test_generate_message_too_long_with_custom_message assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_long, message: 'custom message %{count}', count: 10) end # validates_length_of: generate_message(attr, :too_short, default: custom_message, count: option_value.begin) - def test_generate_message_too_short_with_default_message + def test_generate_message_too_short_with_default_message_plural assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, count: 10) end + def test_generate_message_too_short_with_default_message_singular + assert_equal "is too short (minimum is 1 character)", @person.errors.generate_message(:title, :too_short, count: 1) + end + def test_generate_message_too_short_with_custom_message assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_short, message: 'custom message %{count}', count: 10) end # validates_length_of: generate_message(attr, :wrong_length, message: custom_message, count: option_value) - def test_generate_message_wrong_length_with_default_message + def test_generate_message_wrong_length_with_default_message_plural assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, count: 10) end + def test_generate_message_wrong_length_with_default_message_singular + assert_equal "is the wrong length (should be 1 character)", @person.errors.generate_message(:title, :wrong_length, count: 1) + end + def test_generate_message_wrong_length_with_custom_message assert_equal 'custom message 10', @person.errors.generate_message(:title, :wrong_length, message: 'custom message %{count}', count: 10) end diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 0b27aabf63..e51b5b44cc 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -10,6 +10,13 @@ *James Coleman* +* Rails will now pass a custom validation context through to autosave associations + in order to validate child associations with the same context. + + Fixes #13854. + + *Eric Chahin*, *Aaron Nelson*, *Kevin Casey* + * Stringify all variable keys of mysql connection configuration. When the `sql_mode` variable for mysql adapters is set in the configuration diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 265bad7bc2..ac1479ad8f 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -774,16 +774,15 @@ module ActiveRecord # In the above example posts with no approved comments are not returned at all, because # the conditions apply to the SQL statement as a whole and not just to the association. # + # You must disambiguate column references for this fallback to happen, for example + # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not. + # # If you want to load all posts (including posts with no approved comments) then write # your own LEFT OUTER JOIN query using ON # - # Post.joins('LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = true') - # - # You must disambiguate column references for this fallback to happen, for example - # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not. + # Post.joins("LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = '1'") # - # If you do want eager load only some members of an association it is usually more natural - # to include an association which has conditions defined on it: + # 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' diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index f149d8f127..80cf7572df 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -304,7 +304,8 @@ module ActiveRecord def association_valid?(reflection, record) return true if record.destroyed? || record.marked_for_destruction? - unless valid = record.valid? + 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}" 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 aa99822389..ffa6af6d99 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -71,7 +71,8 @@ module ActiveRecord # column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2) # def column_exists?(table_name, column_name, type = nil, options = {}) - columns(table_name).any?{ |c| c.name == column_name.to_s && + column_name = column_name.to_s + columns(table_name).any?{ |c| c.name == column_name && (!type || c.type == type) && (!options.key?(:limit) || c.limit == options[:limit]) && (!options.key?(:precision) || c.precision == options[:precision]) && diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 78343cf4f5..3b3b03ff6e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -120,7 +120,7 @@ module ActiveRecord end def collector - if @prepared_statements + if prepared_statements SQLString.new else BindCollector.new @@ -388,7 +388,13 @@ module ActiveRecord end def without_prepared_statement?(binds) - !@prepared_statements || binds.empty? + !prepared_statements || binds.empty? + end + + def column_for(table_name, column_name) # :nodoc: + column_name = column_name.to_s + columns(table_name).detect { |c| c.name == column_name } || + raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}") end end end 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 ebce0c0460..4184fad81c 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -711,15 +711,13 @@ module ActiveRecord end def rename_column_sql(table_name, column_name, new_column_name) - options = { name: new_column_name } - - if column = columns(table_name).find { |c| c.name == column_name.to_s } - options[:default] = column.default - options[:null] = column.null - options[:auto_increment] = (column.extra == "auto_increment") - else - raise ActiveRecordError, "No such column: #{table_name}.#{column_name}" - end + column = column_for(table_name, column_name) + options = { + name: new_column_name, + default: column.default, + null: column.null, + auto_increment: column.extra == "auto_increment" + } current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", 'SCHEMA')["Type"] schema_creation.accept ChangeColumnDefinition.new column, current_type, options @@ -757,13 +755,6 @@ module ActiveRecord version[0] >= 5 end - def column_for(table_name, column_name) - unless column = columns(table_name).find { |c| c.name == column_name.to_s } - raise "No such column: #{table_name}.#{column_name}" - end - column - end - def configure_connection variables = @config.fetch(:variables, {}).stringify_keys diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index 1dc7a6f0fd..e7169bd357 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -187,10 +187,6 @@ module ActiveRecord end end - def column_for(table_name, column_name) #:nodoc: - columns(table_name).detect { |c| c.name == column_name.to_s } - end - # Returns the current database name. def current_database query('select current_database()', 'SCHEMA')[0][0] diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 2c6186774f..737f2daa63 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -495,11 +495,9 @@ module ActiveRecord end def rename_column(table_name, column_name, new_column_name) #:nodoc: - unless columns(table_name).detect{|c| c.name == column_name.to_s } - raise ActiveRecord::ActiveRecordError, "Missing column #{table_name}.#{column_name}" - end - alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s}) - rename_column_indexes(table_name, column_name, new_column_name) + column = column_for(table_name, column_name) + alter_table(table_name, rename: {column.name => new_column_name.to_s}) + rename_column_indexes(table_name, column.name, new_column_name) end protected diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 6b0459ea37..9538ead5f1 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -278,7 +278,7 @@ db_namespace = namespace :db do db_namespace['structure:dump'].reenable end - # desc "Recreate the databases from the structure.sql file" + desc "Recreate the databases from the structure.sql file" task :load => [:environment, :load_config] do ActiveRecord::Tasks::DatabaseTasks.load_schema(:sql, ENV['DB_STRUCTURE']) end diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 0b56430b34..42c9881b48 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -242,7 +242,7 @@ module ActiveRecord return 0 if relation.limit_value == 0 query_builder = build_count_subquery(relation, column_name, distinct) - bind_values = relation.bind_values + bind_values = query_builder.bind_values + relation.bind_values else column = aggregate_column(column_name) @@ -389,9 +389,11 @@ module ActiveRecord aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias) relation.select_values = [aliased_column] - subquery = relation.arel.as(subquery_alias) + arel = relation.arel + subquery = arel.as(subquery_alias) sm = Arel::SelectManager.new relation.engine + sm.bind_values = arel.bind_values select_value = operation_over_aggregate_column(column_alias, 'count', distinct) sm.project(select_value).from(subquery) end diff --git a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb index ba89487838..e4b69fdf7b 100644 --- a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb @@ -100,7 +100,7 @@ module ActiveRecord def quoted_id "'zomg'" end - } + }.new assert_raise(TypeError) { @conn.type_cast(quoted_id_obj, nil) } 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 2f5c9d6e1b..2453d6cf58 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -26,6 +26,8 @@ require 'models/reference' require 'models/job' require 'models/college' require 'models/student' +require 'models/pirate' +require 'models/ship' class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase fixtures :authors, :posts, :comments @@ -43,12 +45,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :categories, :companies, :developers, :projects, :developers_projects, :topics, :authors, :comments, :people, :posts, :readers, :taggings, :cars, :essays, - :categorizations, :jobs + :categorizations, :jobs, :tags def setup Client.destroyed_client_ids.clear end + def test_sti_subselect_count + tag = Tag.first + len = Post.tagged_with(tag.id).limit(10).size + assert_operator len, :>, 0 + end + def test_anonymous_has_many developer = Class.new(ActiveRecord::Base) { self.table_name = 'developers' @@ -1877,4 +1885,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end end end + + test 'passes custom context validation to validate children' do + pirate = FamousPirate.new + pirate.famous_ships << ship = FamousShip.new + + assert pirate.valid? + assert_not pirate.valid?(:conference) + assert_equal "can't be blank", ship.errors[:name].first + end end diff --git a/activerecord/test/cases/dup_test.rb b/activerecord/test/cases/dup_test.rb index 1e6ccecfab..409d9a82e2 100644 --- a/activerecord/test/cases/dup_test.rb +++ b/activerecord/test/cases/dup_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require 'models/reply' require 'models/topic' module ActiveRecord @@ -32,6 +33,14 @@ module ActiveRecord assert duped.new_record?, 'topic is new' end + def test_dup_not_destroyed + topic = Topic.first + topic.destroy + + duped = topic.dup + assert_not duped.destroyed? + end + def test_dup_has_no_id topic = Topic.first duped = topic.dup diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 9209672ac5..823146b399 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -234,19 +234,12 @@ class PersistenceTest < ActiveRecord::TestCase end def test_save_with_duping_of_destroyed_object - developer = Developer.create(name: "Kuldeep") + developer = Developer.first developer.destroy new_developer = developer.dup new_developer.save assert new_developer.persisted? - end - - def test_dup_of_destroyed_object_is_not_destroyed - developer = Developer.create(name: "Kuldeep") - developer.destroy - new_developer = developer.dup - new_developer.save - assert_equal new_developer.destroyed?, false + assert_not new_developer.destroyed? end def test_create_many diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index e472cf951d..90a3c3ecee 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -84,3 +84,9 @@ end class DestructivePirate < Pirate has_one :dependent_ship, :class_name => 'Ship', :foreign_key => :pirate_id, :dependent => :destroy end + +class FamousPirate < ActiveRecord::Base + self.table_name = 'pirates' + has_many :famous_ships + validates_presence_of :catchphrase, on: :conference +end
\ No newline at end of file diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb index 3da031946f..77a4728d0b 100644 --- a/activerecord/test/models/ship.rb +++ b/activerecord/test/models/ship.rb @@ -17,3 +17,9 @@ class Ship < ActiveRecord::Base false end end + +class FamousShip < ActiveRecord::Base + self.table_name = 'ships' + belongs_to :famous_pirate + validates_presence_of :name, on: :conference +end diff --git a/activesupport/lib/active_support/core_ext/object/to_json.rb b/activesupport/lib/active_support/core_ext/object/to_json.rb deleted file mode 100644 index f58364f9c6..0000000000 --- a/activesupport/lib/active_support/core_ext/object/to_json.rb +++ /dev/null @@ -1,5 +0,0 @@ -ActiveSupport::Deprecation.warn 'You have required `active_support/core_ext/object/to_json`. ' \ - 'This file will be removed in Rails 4.2. You should require `active_support/core_ext/object/json` ' \ - 'instead.' - -require 'active_support/core_ext/object/json'
\ No newline at end of file diff --git a/activesupport/test/core_ext/object/json_test.rb b/activesupport/test/core_ext/object/json_test.rb deleted file mode 100644 index d3d31530df..0000000000 --- a/activesupport/test/core_ext/object/json_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'abstract_unit' - -class JsonTest < ActiveSupport::TestCase - # See activesupport/test/json/encoding_test.rb for JSON encoding tests - - def test_deprecated_require_to_json_rb - assert_deprecated { require 'active_support/core_ext/object/to_json' } - end -end diff --git a/guides/source/_license.html.erb b/guides/source/_license.html.erb index 00b4466f50..d22f016948 100644 --- a/guides/source/_license.html.erb +++ b/guides/source/_license.html.erb @@ -1,2 +1,2 @@ -<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p> +<p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p> <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index 3cf833dee8..9101ed60d4 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -15,14 +15,5 @@ </p> <% end %> <p> - The guides for Rails 4.1.x are available at <a href="http://guides.rubyonrails.org/v4.1.0/">http://guides.rubyonrails.org/v4.1.0/</a>. -</p> -<p> - The guides for Rails 4.0.x are available at <a href="http://guides.rubyonrails.org/v4.0.4/">http://guides.rubyonrails.org/v4.0.4/</a>. -</p> -<p> - The guides for Rails 3.2.x are available at <a href="http://guides.rubyonrails.org/v3.2.17/">http://guides.rubyonrails.org/v3.2.17/</a>. -</p> -<p> - The guides for Rails 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>. + The guides for earlier releases: <a href="http://guides.rubyonrails.org/v4.1.0/">Rails 4.1.0</a>, <a href="http://guides.rubyonrails.org/v4.0.4/">Rails 4.0.4</a>, <a href="http://guides.rubyonrails.org/v3.2.17/">Rails 3.2.17</a> and <a href="http://guides.rubyonrails.org/v2.3.11/">Rails 2.3.11</a>. </p> diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index fa964e4450..389ffdac6e 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -91,7 +91,7 @@ current version of Ruby installed: TIP. A number of tools exist to help you quickly install Ruby and Ruby on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org), -while Mac OS X users can use [Rails One Click](http://railsoneclick.com). +while Mac OS X users can use [Tokaido](https://github.com/tokaido/tokaidoapp). ```bash $ ruby -v @@ -267,8 +267,9 @@ invoke scss create app/assets/stylesheets/welcome.css.scss ``` -Most important of these are of course the controller, located at `app/controllers/welcome_controller.rb` -and the view, located at `app/views/welcome/index.html.erb`. +Most important of these are of course the controller, located at +`app/controllers/welcome_controller.rb` and the view, located at +`app/views/welcome/index.html.erb`. Open the `app/views/welcome/index.html.erb` file in your text editor. Delete all of the existing code in the file, and replace it with the following single line @@ -433,17 +434,16 @@ class, define a `new` method so that the controller now looks like this: ```ruby class ArticlesController < ApplicationController - def new end - end ``` With the `new` method defined in `ArticlesController`, if you refresh <http://localhost:3000/articles/new> you'll see another error: -![Template is missing for articles/new](images/getting_started/template_is_missing_articles_new.png) +![Template is missing for articles/new] +(images/getting_started/template_is_missing_articles_new.png) You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view @@ -507,7 +507,6 @@ method called `form_for`. To use this method, add this code into ```html+erb <%= form_for :article do |f| %> - <p> <%= f.label :title %><br> <%= f.text_field :title %> @@ -521,7 +520,6 @@ method called `form_for`. To use this method, add this code into <p> <%= f.submit %> </p> - <% end %> ``` @@ -571,11 +569,10 @@ edit_article GET /articles/:id/edit(.:format) articles#edit root GET / welcome#index ``` -The `articles_path` helper tells Rails to point the form -to the URI Pattern associated with the `articles` prefix; and -the form will (by default) send a `POST` request -to that route. This is associated with the -`create` action of the current controller, the `ArticlesController`. +The `articles_path` helper tells Rails to point the form to the URI Pattern +associated with the `articles` prefix; and the form will (by default) send a +`POST` request to that route. This is associated with the `create` action of +the current controller, the `ArticlesController`. With the form and its associated route defined, you will be able to fill in the form and then click the submit button to begin the process of creating a new @@ -596,13 +593,11 @@ underneath the `new` action, as shown: ```ruby class ArticlesController < ApplicationController - def new end def create end - end ``` @@ -641,10 +636,10 @@ parameters but nothing in particular is being done with them. ### Creating the Article model -Models in Rails use a singular name, and their corresponding database tables use -a plural name. Rails provides a generator for creating models, which -most Rails developers tend to use when creating new models. -To create the new model, run this command in your terminal: +Models in Rails use a singular name, and their corresponding database tables +use a plural name. Rails provides a generator for creating models, which most +Rails developers tend to use when creating new models. To create the new model, +run this command in your terminal: ```bash $ rails generate model Article title:string text:text @@ -655,26 +650,23 @@ with a _title_ attribute of type string, and a _text_ attribute of type text. Those attributes are automatically added to the `articles` table in the database and mapped to the `Article` model. -Rails responded by creating a bunch of files. For -now, we're only interested in `app/models/article.rb` and -`db/migrate/20140120191729_create_articles.rb` (your name could be a bit -different). The latter is responsible -for creating the database structure, which is what we'll look at next. +Rails responded by creating a bunch of files. For now, we're only interested +in `app/models/article.rb` and `db/migrate/20140120191729_create_articles.rb` +(your name could be a bit different). The latter is responsible for creating +the database structure, which is what we'll look at next. -TIP: Active Record is smart enough to automatically map column names to -model attributes, which means you don't have to declare attributes -inside Rails models, as that will be done automatically by Active -Record. +TIP: Active Record is smart enough to automatically map column names to model +attributes, which means you don't have to declare attributes inside Rails +models, as that will be done automatically by Active Record. ### Running a Migration -As we've just seen, `rails generate model` created a _database -migration_ file inside the `db/migrate` directory. -Migrations are Ruby classes that are designed to make it simple to -create and modify database tables. Rails uses rake commands to run migrations, -and it's possible to undo a migration after it's been applied to your database. -Migration filenames include a timestamp to ensure that they're processed in the -order that they were created. +As we've just seen, `rails generate model` created a _database migration_ file +inside the `db/migrate` directory. Migrations are Ruby classes that are +designed to make it simple to create and modify database tables. Rails uses +rake commands to run migrations, and it's possible to undo a migration after +it's been applied to your database. Migration filenames include a timestamp to +ensure that they're processed in the order that they were created. If you look in the `db/migrate/20140120191729_create_articles.rb` file (remember, yours will have a slightly different name), here's what you'll find: @@ -699,8 +691,8 @@ in case you want to reverse it later. When you run this migration it will create an `articles` table with one string column and a text column. It also creates two timestamp fields to allow Rails to track article creation and update times. -TIP: For more information about migrations, refer to [Rails Database -Migrations](migrations.html). +TIP: For more information about migrations, refer to [Rails Database Migrations] +(migrations.html). At this point, you can use a rake command to run the migration: @@ -742,50 +734,47 @@ end Here's what's going on: every Rails model can be initialized with its respective attributes, which are automatically mapped to the respective -database columns. In the first line we do just that -(remember that `params[:article]` contains the attributes we're interested in). -Then, `@article.save` is responsible for saving the model in the database. -Finally, we redirect the user to the `show` action, which we'll define later. +database columns. In the first line we do just that (remember that +`params[:article]` contains the attributes we're interested in). Then, +`@article.save` is responsible for saving the model in the database. Finally, +we redirect the user to the `show` action, which we'll define later. -TIP: As we'll see later, `@article.save` returns a boolean indicating -whether the article was saved or not. +TIP: As we'll see later, `@article.save` returns a boolean indicating whether +the article was saved or not. -If you now go to -<http://localhost:3000/articles/new> you'll *almost* be able to create an -article. Try it! You should get an error that looks like this: +If you now go to <http://localhost:3000/articles/new> you'll *almost* be able +to create an article. Try it! You should get an error that looks like this: -![Forbidden attributes for new article](images/getting_started/forbidden_attributes_for_new_article.png) +![Forbidden attributes for new article] +(images/getting_started/forbidden_attributes_for_new_article.png) Rails has several security features that help you write secure applications, -and you're running into one of them now. This one is called -`[strong_parameters](http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters)`, -which requires us to tell Rails exactly which parameters are allowed into -our controller actions. - -Why do you have to bother? The ability to grab and automatically assign -all controller parameters to your model in one shot makes the programmer's -job easier, but this convenience also allows malicious use. What if a -request to the server was crafted to look like a new article form submit -but also included extra fields with values that violated your applications -integrity? They would be 'mass assigned' into your model and then into the -database along with the good stuff - potentially breaking your application -or worse. - -We have to whitelist our controller parameters to prevent wrongful -mass assignment. In this case, we want to both allow and require the -`title` and `text` parameters for valid use of `create`. The syntax for -this introduces `require` and `permit`. The change will involve one line -in the `create` action: +and you're running into one of them now. This one is called `[strong_parameters] +(http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters)`, +which requires us to tell Rails exactly which parameters are allowed into our +controller actions. + +Why do you have to bother? The ability to grab and automatically assign all +controller parameters to your model in one shot makes the programmer's job +easier, but this convenience also allows malicious use. What if a request to +the server was crafted to look like a new article form submit but also included +extra fields with values that violated your applications integrity? They would +be 'mass assigned' into your model and then into the database along with the +good stuff - potentially breaking your application or worse. + +We have to whitelist our controller parameters to prevent wrongful mass +assignment. In this case, we want to both allow and require the `title` and +`text` parameters for valid use of `create`. The syntax for this introduces +`require` and `permit`. The change will involve one line in the `create` action: ```ruby @article = Article.new(params.require(:article).permit(:title, :text)) ``` -This is often factored out into its own method so it can be reused by -multiple actions in the same controller, for example `create` and `update`. -Above and beyond mass assignment issues, the method is often made -`private` to make sure it can't be called outside its intended context. -Here is the result: +This is often factored out into its own method so it can be reused by multiple +actions in the same controller, for example `create` and `update`. Above and +beyond mass assignment issues, the method is often made `private` to make sure +it can't be called outside its intended context. Here is the result: ```ruby def create @@ -802,13 +791,14 @@ private ``` TIP: For more information, refer to the reference above and -[this blog article about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). +[this blog article about Strong Parameters] +(http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). ### Showing Articles -If you submit the form again now, Rails will complain about not finding -the `show` action. That's not very useful though, so let's add the -`show` action before proceeding. +If you submit the form again now, Rails will complain about not finding the +`show` action. That's not very useful though, so let's add the `show` action +before proceeding. As we have seen in the output of `rake routes`, the route for `show` action is as follows: @@ -824,17 +814,15 @@ As we did before, we need to add the `show` action in `app/controllers/articles_controller.rb` and its respective view. NOTE: A frequent practice is to place the standard CRUD actions in each -controller in the following order: `index`, `show`, `new`, `edit`, `create`, -`update` and `destroy`. You may use any order you choose, but keep in mind that -these are public methods; as mentioned earlier in this guide, they must be -placed before any private or protected method in the controller in order to -work. +controller in the following order: `index`, `show`, `new`, `edit`, `create`, `update` +and `destroy`. You may use any order you choose, but keep in mind that these +are public methods; as mentioned earlier in this guide, they must be placed +before any private or protected method in the controller in order to work. Given that, let's add the `show` action, as follows: ```ruby class ArticlesController < ApplicationController - def show @article = Article.find(params[:id]) end @@ -887,7 +875,6 @@ first method in the controller. Let's do it: ```ruby class ArticlesController < ApplicationController - def index @articles = Article.all end @@ -981,9 +968,9 @@ article can go back and view the whole list again: <%= link_to 'Back', articles_path %> ``` -TIP: If you want to link to an action in the same controller, you don't -need to specify the `:controller` option, as Rails will use the current -controller by default. +TIP: If you want to link to an action in the same controller, you don't need to +specify the `:controller` option, as Rails will use the current controller by +default. TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop @@ -1341,8 +1328,8 @@ The reason we can use this shorter, simpler `form_for` declaration to stand in for either of the other forms is that `@article` is a *resource* corresponding to a full set of RESTful routes, and Rails is able to infer which URI and method to use. -For more information about this use of `form_for`, see -[Resource-oriented style](//api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for-label-Resource-oriented+style). +For more information about this use of `form_for`, see [Resource-oriented style] +(http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for-label-Resource-oriented+style). Now, let's update the `app/views/articles/new.html.erb` view to use this new partial, rewriting it completely: @@ -1403,7 +1390,6 @@ The complete `ArticlesController` in the ```ruby class ArticlesController < ApplicationController - def index @articles = Article.all end @@ -1459,8 +1445,7 @@ them from the database. Note that we don't need to add a view for this action since we're redirecting to the `index` action. Finally, add a 'Destroy' link to your `index` action template -(`app/views/articles/index.html.erb`) to wrap everything -together. +(`app/views/articles/index.html.erb`) to wrap everything together. ```html+erb <h1>Listing Articles</h1> |