diff options
17 files changed, 88 insertions, 49 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index e7e414571d..f6f7de7fbc 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,10 @@ +* `ActiveRecord::FinderMethods.find` with block can handle proc parameter as + `Enumerable#find` does. + + Fixes #15382. + + *James Yang* + * Make timezone aware attributes work with PostgreSQL array columns. Fixes #13402. @@ -532,10 +539,6 @@ *Luke Steensen* -* Make possible to change `record_timestamps` inside Callbacks. - - *Tieg Zaharia* - * Fixed error where .persisted? throws SystemStackError for an unsaved model with a custom primary key that didn't save due to validation error. diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 07dfc448e7..6222bfe903 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1577,7 +1577,7 @@ module ActiveRecord scope = nil end - habtm_reflection = ActiveRecord::Reflection::AssociationReflection.new(:has_and_belongs_to_many, name, scope, options, self) + habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(:has_and_belongs_to_many, name, scope, options, self) builder = Builder::HasAndBelongsToMany.new name, self, options diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index 4a04303fb8..f1c36cd047 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -179,7 +179,7 @@ module ActiveRecord def creation_attributes attributes = {} - if (reflection.macro == :has_one || reflection.macro == :has_many) && !options[:through] + if (reflection.has_one? || reflection.collection?) && !options[:through] attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key] if reflection.options[:as] diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index 1edd4fa3aa..81fdd681de 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -92,7 +92,7 @@ module ActiveRecord # has_one associations. def invertible_for?(record) inverse = inverse_reflection_for(record) - inverse && inverse.macro == :has_one + inverse && inverse.has_one? end def target_id diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index f6e08991f7..da9b125fd6 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -105,9 +105,9 @@ module ActiveRecord inverse = source_reflection.inverse_of if inverse - if inverse.macro == :has_many + if inverse.collection? record.send(inverse.name) << build_through_record(record) - elsif inverse.macro == :has_one + elsif inverse.has_one? record.send("#{inverse.name}=", build_through_record(record)) end end @@ -170,7 +170,7 @@ module ActiveRecord klass.decrement_counter counter, records.map(&:id) end - if through_reflection.macro == :has_many && update_through_counter?(method) + if through_reflection.collection? && update_through_counter?(method) update_counter(-count, through_reflection) end @@ -187,7 +187,7 @@ module ActiveRecord records.each do |record| through_records = through_records_for(record) - if through_reflection.macro == :has_many + if through_reflection.collection? through_records.each { |r| through_association.target.delete(r) } else if through_records.include?(through_association.target) diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 74e2a8e6b9..b3c3e26c9f 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -187,7 +187,7 @@ module ActiveRecord # Doesn't use after_save as that would save associations added in after_create/after_update twice after_create save_method after_update save_method - elsif reflection.macro == :has_one + elsif reflection.has_one? define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method) # Configures two callbacks instead of a single after_save so that # the model may rely on their execution order relative to its diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index e8c067f758..e4d0abb8ef 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -311,8 +311,8 @@ module ActiveRecord #:nodoc: include Locking::Optimistic include Locking::Pessimistic include AttributeMethods - include Timestamp include Callbacks + include Timestamp include Associations include ActiveModel::SecurePassword include AutosaveAssociation diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 4d5203612c..24f3de019d 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -228,7 +228,7 @@ module ActiveRecord def initialize(macro, name, scope, options, active_record) super - @collection = [:has_many, :has_and_belongs_to_many].include?(macro) + @collection = macro == :has_many @automatic_inverse_of = nil @type = options[:as] && "#{options[:as]}_type" @foreign_type = options[:foreign_type] || "#{name}_type" @@ -392,7 +392,7 @@ Joining, Preloading and eager loading of these associations is deprecated and wi # * you use autosave; <tt>autosave: true</tt> # * the association is a +has_many+ association def validate? - !options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many) + !options[:validate].nil? ? options[:validate] : (options[:autosave] == true || collection?) end # Returns +true+ if +self+ is a +belongs_to+ reflection. @@ -400,6 +400,10 @@ Joining, Preloading and eager loading of these associations is deprecated and wi macro == :belongs_to end + def has_one? + macro == :has_one + end + def association_class case macro when :belongs_to @@ -538,6 +542,13 @@ Joining, Preloading and eager loading of these associations is deprecated and wi end end + class HasAndBelongsToManyReflection < AssociationReflection #:nodoc: + def initialize(macro, name, scope, options, active_record) + super + @collection = true + end + end + # Holds all the meta-data about a :through association as it was specified # in the Active Record class. class ThroughReflection < AssociationReflection #:nodoc: @@ -739,7 +750,7 @@ directive on your declaration like: raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection) end - if macro == :has_one && through_reflection.collection? + if has_one? && through_reflection.collection? raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection) end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 47e90e9021..0c9c761f97 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -65,7 +65,7 @@ module ActiveRecord # # returns an Array of the required fields, available since Rails 3.1. def find(*args) if block_given? - to_a.find { |*block_args| yield(*block_args) } + to_a.find(*args) { |*block_args| yield(*block_args) } else find_with_ids(*args) end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index c0440744e9..0f52f2c0fc 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -33,6 +33,17 @@ class FinderTest < ActiveRecord::TestCase assert_equal(topics(:first).title, Topic.find(1).title) end + def test_find_with_proc_parameter_and_block + e = assert_raises(RuntimeError) do + Topic.all.find(-> { raise "should happen" }) { |e| e.title == "non-existing-title" } + end + assert_equal "should happen", e.message + + assert_nothing_raised(RuntimeError) do + Topic.all.find(-> { raise "should not happen" }) { |e| e.title == topics(:first).title } + end + end + def test_find_passing_active_record_object_is_deprecated assert_deprecated do Topic.find(Topic.last) diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index e2a18d138d..5f02d39e32 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -394,7 +394,7 @@ class SchemaDumperTest < ActiveRecord::TestCase output = standard_dump assert_no_match %r{create_table "foo_.+_bar"}, output - assert_no_match %r{create_index "foo_.+_bar"}, output + assert_no_match %r{add_index "foo_.+_bar"}, output assert_no_match %r{create_table "schema_migrations"}, output ensure migration.migrate(:down) diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 77ab427be0..0472246f71 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -71,24 +71,6 @@ class TimestampTest < ActiveRecord::TestCase assert_equal @previously_updated_at, @developer.updated_at end - def test_saving_when_callback_sets_record_timestamps_to_false_doesnt_update_its_timestamp - klass = Class.new(Developer) do - before_update :cancel_record_timestamps - def cancel_record_timestamps - self.record_timestamps = false - return true - end - end - - developer = klass.first - previously_updated_at = developer.updated_at - - developer.name = "New Name" - developer.save! - - assert_equal previously_updated_at, developer.updated_at - end - def test_touching_an_attribute_updates_timestamp previously_created_at = @developer.created_at @developer.touch(:created_at) @@ -399,6 +381,19 @@ class TimestampTest < ActiveRecord::TestCase assert_not_equal time, pet.updated_at end + def test_timestamp_column_values_are_present_in_the_callbacks + klass = Class.new(ActiveRecord::Base) do + self.table_name = 'people' + + before_create do + self.born_at = self.created_at + end + end + + person = klass.create first_name: 'David' + assert_not_equal person.born_at, nil + end + def test_timestamp_attributes_for_create toy = Toy.first assert_equal [:created_at, :created_on], toy.send(:timestamp_attributes_for_create) diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 5f459cf682..98fd0b6803 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -529,6 +529,7 @@ ActiveRecord::Schema.define do t.references :best_friend t.references :best_friend_of t.integer :insures, null: false, default: 0 + t.timestamp :born_at t.timestamps end diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index e782cfa2f5..e1eb81b8bc 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -57,7 +57,7 @@ module ActiveSupport def initialize(constructor = {}) if constructor.respond_to?(:to_hash) super() - update(constructor.to_hash) + update(constructor) else super(constructor) end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index cd0cb1a144..f18172a5ce 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -659,6 +659,14 @@ class HashExtTest < ActiveSupport::TestCase assert_equal 1, h['first'] end + def test_to_options_on_indifferent_preserves_works_as_hash_with_dup + h = HashWithIndifferentAccess.new({ a: { b: 'b' } }) + dup = h.dup + + dup[:a][:c] = 'c' + assert_equal 'c', h[:a][:c] + end + def test_indifferent_sub_hashes h = {'user' => {'id' => 5}}.with_indifferent_access ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}} diff --git a/guides/source/migrations.md b/guides/source/active_record_migrations.md index 9568bfcdb8..5a550d9e55 100644 --- a/guides/source/migrations.md +++ b/guides/source/active_record_migrations.md @@ -293,17 +293,10 @@ end You can append as many column name/type pairs as you want. -### Supported Type Modifiers +### Passing Modifiers -You can also specify some options just after the field type between curly -braces. You can use the following modifiers: - -* `limit` Sets the maximum size of the `string/text/binary/integer` fields. -* `precision` Defines the precision for the `decimal` fields, representing the total number of digits in the number. -* `scale` Defines the scale for the `decimal` fields, representing the number of digits after the decimal point. -* `polymorphic` Adds a `type` column for `belongs_to` associations. -* `null` Allows or disallows `NULL` values in the column. -* `default` Allows to set a default value on the column. NOTE: If using a dynamic value (such as date), the default will only be calculated the first time (e.g. on the date the migration is applied.) +Some commonly used [type modifiers](#column-modifiers) can be passed directly on +the command line. They are enclosed by curly braces and follow the field type: For instance, running: @@ -322,6 +315,8 @@ class AddDetailsToProducts < ActiveRecord::Migration end ``` +TIP: Have a look at the generators help output for further details. + Writing a Migration ------------------- @@ -439,6 +434,21 @@ change_column_default :products, :approved, false This sets `:name` field on products to a `NOT NULL` column and the default value of the `:approved` field to false. +### Column Modifiers + +Column modifiers can be applied when creating or changing a column: + +* `limit` Sets the maximum size of the `string/text/binary/integer` fields. +* `precision` Defines the precision for the `decimal` fields, representing the total number of digits in the number. +* `scale` Defines the scale for the `decimal` fields, representing the number of digits after the decimal point. +* `polymorphic` Adds a `type` column for `belongs_to` associations. +* `null` Allows or disallows `NULL` values in the column. +* `default` Allows to set a default value on the column. NOTE: If using a dynamic value (such as date), the default will only be calculated the first time (e.g. on the date the migration is applied.) +* `index` Adds an index for the column. + +Some adapters may support additional options; see the adapter specific API docs +for further information. + ### When Helpers aren't Enough If the helpers provided by Active Record aren't enough you can use the `execute` diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 5138412312..82e248ee38 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -13,8 +13,8 @@ url: active_record_basics.html description: This guide will get you started with models, persistence to database and the Active Record pattern and library. - - name: Rails Database Migrations - url: migrations.html + name: Active Record Migrations + url: active_record_migrations.html description: This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner. - name: Active Record Validations |