From da636809daca9c338200811d3590e446f57c8e81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 1 Sep 2009 13:11:15 +0200 Subject: Assert primary key does not exist in habtm when the association is defined, instead of doing that everytime a record is inserted. [#3128 state:committed] Signed-off-by: Jeremy Kemper --- activerecord/lib/active_record/associations.rb | 24 +++++++++++----------- .../has_and_belongs_to_many_association.rb | 16 --------------- 2 files changed, 12 insertions(+), 28 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index f494e38e2f..1c20af9adb 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -60,6 +60,12 @@ module ActiveRecord end end + class HasAndBelongsToManyAssociationWithPrimaryKeyError < ActiveRecordError #:nodoc: + def initialize(reflection) + super("Primary key is not allowed in a has_and_belongs_to_many join table (#{reflection.options[:join_table]}).") + end + end + class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc: def initialize(reflection) super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.") @@ -1652,16 +1658,19 @@ module ActiveRecord def create_has_and_belongs_to_many_reflection(association_id, options, &extension) options.assert_valid_keys(valid_keys_for_has_and_belongs_to_many_association) - options[:extend] = create_extension_modules(association_id, extension, options[:extend]) reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self) - + reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name)) + if reflection.association_foreign_key == reflection.primary_key_name raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection) end - reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name)) + if connection.supports_primary_key? && + (connection.primary_key(reflection.options[:join_table]) rescue false) + raise HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection) + end reflection end @@ -1670,15 +1679,6 @@ module ActiveRecord [ associations ].flatten.collect { |association| reflect_on_association(association.to_s.intern) } end - def guard_against_unlimitable_reflections(reflections, options) - if (options[:offset] || options[:limit]) && !using_limitable_reflections?(reflections) - raise( - ConfigurationError, - "You can not use offset and limit together with has_many or has_and_belongs_to_many associations" - ) - end - end - def select_all_rows(options, join_dependency) connection.select_all( construct_finder_sql_with_included_associations(options, join_dependency), diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index d91c555dad..fd23e59e82 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -1,11 +1,6 @@ module ActiveRecord module Associations class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc: - def initialize(owner, reflection) - super - @primary_key_list = {} - end - def create(attributes = {}) create_record(attributes) { |record| insert_record(record) } end @@ -22,12 +17,6 @@ module ActiveRecord @reflection.reset_column_information end - def has_primary_key? - return @has_primary_key unless @has_primary_key.nil? - @has_primary_key = (ActiveRecord::Base.connection.supports_primary_key? && - ActiveRecord::Base.connection.primary_key(@reflection.options[:join_table])) - end - protected def construct_find_options!(options) options[:joins] = @join_sql @@ -40,11 +29,6 @@ module ActiveRecord end def insert_record(record, force = true, validate = true) - if has_primary_key? - raise ActiveRecord::ConfigurationError, - "Primary key is not allowed in a has_and_belongs_to_many join table (#{@reflection.options[:join_table]})." - end - if record.new_record? if force record.save! -- cgit v1.2.3 From e870e24887e829547abdb6592d614c52f5412132 Mon Sep 17 00:00:00 2001 From: Jeffrey Hardy Date: Wed, 2 Sep 2009 11:20:52 -0500 Subject: Don't try to log protected attribute removal if there's no logger defined [#3135 state:resolved] Signed-off-by: Joshua Peek --- activerecord/lib/active_record/base.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index c5be561ea3..72742cb57c 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2943,7 +2943,9 @@ module ActiveRecord #:nodoc: end def log_protected_attribute_removal(*attributes) - logger.debug "WARNING: Can't mass-assign these protected attributes: #{attributes.join(', ')}" + if logger + logger.debug "WARNING: Can't mass-assign these protected attributes: #{attributes.join(', ')}" + end end # The primary key and inheritance column can never be set by mass-assignment for security reasons. -- cgit v1.2.3 From 3b6a9a020e7e6f71ab6f9ffcf1ef59c57437ca69 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 2 Sep 2009 13:55:02 -0700 Subject: Revert "Assert primary key does not exist in habtm when the association is defined, instead of doing that everytime a record is inserted." Test failures on PostgreSQL. [#3128 state:open] This reverts commit da636809daca9c338200811d3590e446f57c8e81. --- activerecord/lib/active_record/associations.rb | 22 +++++++++++----------- .../has_and_belongs_to_many_association.rb | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 1c20af9adb..02dfb7b400 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -60,12 +60,6 @@ module ActiveRecord end end - class HasAndBelongsToManyAssociationWithPrimaryKeyError < ActiveRecordError #:nodoc: - def initialize(reflection) - super("Primary key is not allowed in a has_and_belongs_to_many join table (#{reflection.options[:join_table]}).") - end - end - class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc: def initialize(reflection) super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.") @@ -1658,19 +1652,16 @@ module ActiveRecord def create_has_and_belongs_to_many_reflection(association_id, options, &extension) options.assert_valid_keys(valid_keys_for_has_and_belongs_to_many_association) + options[:extend] = create_extension_modules(association_id, extension, options[:extend]) reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self) - reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name)) if reflection.association_foreign_key == reflection.primary_key_name raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection) end - if connection.supports_primary_key? && - (connection.primary_key(reflection.options[:join_table]) rescue false) - raise HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection) - end + reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name)) reflection end @@ -1679,6 +1670,15 @@ module ActiveRecord [ associations ].flatten.collect { |association| reflect_on_association(association.to_s.intern) } end + def guard_against_unlimitable_reflections(reflections, options) + if (options[:offset] || options[:limit]) && !using_limitable_reflections?(reflections) + raise( + ConfigurationError, + "You can not use offset and limit together with has_many or has_and_belongs_to_many associations" + ) + end + end + def select_all_rows(options, join_dependency) connection.select_all( construct_finder_sql_with_included_associations(options, join_dependency), diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index fd23e59e82..d91c555dad 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -1,6 +1,11 @@ module ActiveRecord module Associations class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc: + def initialize(owner, reflection) + super + @primary_key_list = {} + end + def create(attributes = {}) create_record(attributes) { |record| insert_record(record) } end @@ -17,6 +22,12 @@ module ActiveRecord @reflection.reset_column_information end + def has_primary_key? + return @has_primary_key unless @has_primary_key.nil? + @has_primary_key = (ActiveRecord::Base.connection.supports_primary_key? && + ActiveRecord::Base.connection.primary_key(@reflection.options[:join_table])) + end + protected def construct_find_options!(options) options[:joins] = @join_sql @@ -29,6 +40,11 @@ module ActiveRecord end def insert_record(record, force = true, validate = true) + if has_primary_key? + raise ActiveRecord::ConfigurationError, + "Primary key is not allowed in a has_and_belongs_to_many join table (#{@reflection.options[:join_table]})." + end + if record.new_record? if force record.save! -- cgit v1.2.3 From 6dc9ad80e6ee4a581c5ace005632373fe7275c03 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 5 Sep 2009 19:10:21 -0500 Subject: Fix warnings in AMo --- activerecord/lib/active_record/callbacks.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 4a2ec5bf95..dd509b6c6a 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -227,7 +227,7 @@ module ActiveRecord end include ActiveSupport::Callbacks - define_callbacks *CALLBACKS + define_callbacks(*CALLBACKS) end # Is called when the object was instantiated by one of the finders, like Base.find. -- cgit v1.2.3 From 4f37b97033f596ec2c95eb53e9964e051c224981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 8 Sep 2009 10:10:14 -0500 Subject: Changed ActiveRecord to use new callbacks and speed up observers by only notifying events that are actually being consumed. Signed-off-by: Joshua Peek --- activerecord/lib/active_record/associations.rb | 53 +++-- activerecord/lib/active_record/base.rb | 11 +- activerecord/lib/active_record/callbacks.rb | 255 ++++++++++++------------- activerecord/lib/active_record/observer.rb | 20 +- activerecord/lib/active_record/validations.rb | 35 +--- 5 files changed, 185 insertions(+), 189 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 02dfb7b400..72061a1b31 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1491,24 +1491,43 @@ module ActiveRecord end before_destroy method_name when :delete_all - module_eval %Q{ - before_destroy do |record| # before_destroy do |record| - delete_all_has_many_dependencies(record, # delete_all_has_many_dependencies(record, - "#{reflection.name}", # "posts", - #{reflection.class_name}, # Post, - %@#{dependent_conditions}@) # %@...@) # this is a string literal like %(...) - end # end - } + # before_destroy do |record| + # self.class.send(:delete_all_has_many_dependencies, + # record, + # "posts", + # Post, + # %@...@) # this is a string literal like %(...) + # end + # end + module_eval <<-CALLBACK + before_destroy do |record| + self.class.send(:delete_all_has_many_dependencies, + record, + "#{reflection.name}", + #{reflection.class_name}, + %@#{dependent_conditions}@) + end + CALLBACK when :nullify - module_eval %Q{ - before_destroy do |record| # before_destroy do |record| - nullify_has_many_dependencies(record, # nullify_has_many_dependencies(record, - "#{reflection.name}", # "posts", - #{reflection.class_name}, # Post, - "#{reflection.primary_key_name}", # "user_id", - %@#{dependent_conditions}@) # %@...@) # this is a string literal like %(...) - end # end - } + # before_destroy do |record| + # self.class.send(:nullify_has_many_dependencies, + # record, + # "posts", + # Post, + # "user_id", + # %@...@) # this is a string literal like %(...) + # end + # end + module_eval <<-CALLBACK + before_destroy do |record| + self.class.send(:nullify_has_many_dependencies, + record, + "#{reflection.name}", + #{reflection.class_name}, + "#{reflection.primary_key_name}", + %@#{dependent_conditions}@) + end + CALLBACK else raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, or :nullify (#{reflection.options[:dependent].inspect})" end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 72742cb57c..afa4185c60 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1679,13 +1679,8 @@ module ActiveRecord #:nodoc: object.instance_variable_set("@attributes", record) object.instance_variable_set("@attributes_cache", Hash.new) - if object.respond_to_without_attributes?(:after_find) - object.send(:callback, :after_find) - end - - if object.respond_to_without_attributes?(:after_initialize) - object.send(:callback, :after_initialize) - end + object.send(:_run_find_callbacks) + object.send(:_run_initialize_callbacks) object end @@ -2438,7 +2433,7 @@ module ActiveRecord #:nodoc: self.attributes = attributes unless attributes.nil? self.class.send(:scope, :create).each { |att,value| self.send("#{att}=", value) } if self.class.send(:scoped?, :create) result = yield self if block_given? - callback(:after_initialize) if respond_to_without_attributes?(:after_initialize) + _run_initialize_callbacks result end diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index dd509b6c6a..361c7b2ef4 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -10,16 +10,14 @@ module ActiveRecord # * (-) save # * (-) valid # * (1) before_validation - # * (2) before_validation_on_create # * (-) validate # * (-) validate_on_create - # * (3) after_validation - # * (4) after_validation_on_create - # * (5) before_save - # * (6) before_create + # * (2) after_validation + # * (3) before_save + # * (4) before_create # * (-) create - # * (7) after_create - # * (8) after_save + # * (5) after_create + # * (6) after_save # # That's a total of eight callbacks, which gives you immense power to react and prepare for each state in the # Active Record lifecycle. The sequence for calling Base#save for an existing record is similar, except that each @@ -212,162 +210,161 @@ module ActiveRecord # instead of quietly returning +false+. module Callbacks extend ActiveSupport::Concern + include ActiveSupport::NewCallbacks - CALLBACKS = %w( - after_find after_initialize before_save after_save before_create after_create before_update after_update before_validation - after_validation before_validation_on_create after_validation_on_create before_validation_on_update - after_validation_on_update before_destroy after_destroy - ) + CALLBACKS = [ + :after_initialize, :after_find, :before_validation, :after_validation, + :before_save, :after_save, :before_create, :after_create, :before_update, + :after_update, :before_destroy, :after_destroy + ] included do - extend Observable - [:create_or_update, :valid?, :create, :update, :destroy].each do |method| alias_method_chain method, :callbacks end - include ActiveSupport::Callbacks - define_callbacks(*CALLBACKS) + define_callbacks :initialize, :find, :save, :create, :update, :destroy, :validation, "result == false" end - # Is called when the object was instantiated by one of the finders, like Base.find. - #def after_find() end - - # Is called after the object has been instantiated by a call to Base.new. - #def after_initialize() end - - # Is called _before_ Base.save (regardless of whether it's a +create+ or +update+ save). - def before_save() end + module ClassMethods + def after_initialize(*args, &block) + options = args.extract_options! + options[:prepend] = true + set_callback(:initialize, :after, *(args << options), &block) + end - # Is called _after_ Base.save (regardless of whether it's a +create+ or +update+ save). - # Note that this callback is still wrapped in the transaction around +save+. For example, if you - # invoke an external indexer at this point it won't see the changes in the database. - # - # class Contact < ActiveRecord::Base - # after_save { logger.info( 'New contact saved!' ) } - # end - def after_save() end - def create_or_update_with_callbacks #:nodoc: - return false if callback(:before_save) == false - if result = create_or_update_without_callbacks - callback(:after_save) + def after_find(*args, &block) + options = args.extract_options! + options[:prepend] = true + set_callback(:find, :after, *(args << options), &block) end - result - end - private :create_or_update_with_callbacks - # Is called _before_ Base.save on new objects that haven't been saved yet (no record exists). - def before_create() end + def before_save(*args, &block) + set_callback(:save, :before, *args, &block) + end - # Is called _after_ Base.save on new objects that haven't been saved yet (no record exists). - # Note that this callback is still wrapped in the transaction around +save+. For example, if you - # invoke an external indexer at this point it won't see the changes in the database. - # - # class Contact < ActiveRecord::Base - # after_create { |record| logger.info( "Contact #{record.id} was created." ) } - # end - def after_create() end - def create_with_callbacks #:nodoc: - return false if callback(:before_create) == false - result = create_without_callbacks - callback(:after_create) - result - end - private :create_with_callbacks + def around_save(*args, &block) + set_callback(:save, :around, *args, &block) + end - # Is called _before_ Base.save on existing objects that have a record. - # - # class Contact < ActiveRecord::Base - # before_update { |record| logger.info( "Contact #{record.id} is about to be updated." ) } - # end - def before_update() end + def after_save(*args, &block) + options = args.extract_options! + options[:prepend] = true + options[:if] = Array(options[:if]) << "!halted && value != false" + set_callback(:save, :after, *(args << options), &block) + end - # Is called _after_ Base.save on existing objects that have a record. - # Note that this callback is still wrapped in the transaction around +save+. For example, if you - # invoke an external indexer at this point it won't see the changes in the database. - # - # class Contact < ActiveRecord::Base - # after_update { |record| logger.info( "Contact #{record.id} was updated." ) } - # end - def after_update() end + def before_create(*args, &block) + set_callback(:create, :before, *args, &block) + end - def update_with_callbacks(*args) #:nodoc: - return false if callback(:before_update) == false - result = update_without_callbacks(*args) - callback(:after_update) - result - end - private :update_with_callbacks + def around_create(*args, &block) + set_callback(:create, :around, *args, &block) + end - # Is called _before_ Validations.validate (which is part of the Base.save call). - def before_validation() end + def after_create(*args, &block) + options = args.extract_options! + options[:prepend] = true + options[:if] = Array(options[:if]) << "!halted && value != false" + set_callback(:create, :after, *(args << options), &block) + end - # Is called _after_ Validations.validate (which is part of the Base.save call). - def after_validation() end + def before_update(*args, &block) + set_callback(:update, :before, *args, &block) + end - # Is called _before_ Validations.validate (which is part of the Base.save call) on new objects - # that haven't been saved yet (no record exists). - def before_validation_on_create() end + def around_update(*args, &block) + set_callback(:update, :around, *args, &block) + end - # Is called _after_ Validations.validate (which is part of the Base.save call) on new objects - # that haven't been saved yet (no record exists). - def after_validation_on_create() end + def after_update(*args, &block) + options = args.extract_options! + options[:prepend] = true + options[:if] = Array(options[:if]) << "!halted && value != false" + set_callback(:update, :after, *(args << options), &block) + end - # Is called _before_ Validations.validate (which is part of the Base.save call) on - # existing objects that have a record. - def before_validation_on_update() end + def before_destroy(*args, &block) + set_callback(:destroy, :before, *args, &block) + end - # Is called _after_ Validations.validate (which is part of the Base.save call) on - # existing objects that have a record. - def after_validation_on_update() end + def around_destroy(*args, &block) + set_callback(:destroy, :around, *args, &block) + end - def valid_with_callbacks? #:nodoc: - return false if callback(:before_validation) == false - if new_record? then result = callback(:before_validation_on_create) else result = callback(:before_validation_on_update) end - return false if false == result + def after_destroy(*args, &block) + options = args.extract_options! + options[:prepend] = true + options[:if] = Array(options[:if]) << "!halted && value != false" + set_callback(:destroy, :after, *(args << options), &block) + end - result = valid_without_callbacks? + def before_validation(*args, &block) + options = args.extract_options! + if options[:on] + options[:if] = Array(options[:if]) + options[:if] << "@_on_validate == :#{options[:on]}" + end + set_callback(:validation, :before, *(args << options), &block) + end - callback(:after_validation) - if new_record? then callback(:after_validation_on_create) else callback(:after_validation_on_update) end + def after_validation(*args, &block) + options = args.extract_options! + options[:if] = Array(options[:if]) + options[:if] << "!halted" + options[:if] << "@_on_validate == :#{options[:on]}" if options[:on] + options[:prepend] = true + set_callback(:validation, :after, *(args << options), &block) + end - return result + def method_added(meth) + super + if CALLBACKS.include?(meth.to_sym) + ActiveSupport::Deprecation.warn("Base##{meth} has been deprecated, please use Base.#{meth} :method instead", caller[0,1]) + send(meth.to_sym, meth.to_sym) + end + end end - # Is called _before_ Base.destroy. - # - # Note: If you need to _destroy_ or _nullify_ associated records first, - # use the :dependent option on your associations. - # - # class Contact < ActiveRecord::Base - # after_destroy { |record| logger.info( "Contact #{record.id} is about to be destroyed." ) } - # end - def before_destroy() end + def create_or_update_with_callbacks #:nodoc: + _run_save_callbacks do + create_or_update_without_callbacks + end + end + private :create_or_update_with_callbacks - # Is called _after_ Base.destroy (and all the attributes have been frozen). - # - # class Contact < ActiveRecord::Base - # after_destroy { |record| logger.info( "Contact #{record.id} was destroyed." ) } - # end - def after_destroy() end - def destroy_with_callbacks #:nodoc: - return false if callback(:before_destroy) == false - result = destroy_without_callbacks - callback(:after_destroy) - result + def create_with_callbacks #:nodoc: + _run_create_callbacks do + create_without_callbacks + end end + private :create_with_callbacks - private - def callback(method) - result = run_callbacks(method) { |result, object| false == result } + def update_with_callbacks(*args) #:nodoc: + _run_update_callbacks do + update_without_callbacks(*args) + end + end + private :update_with_callbacks - if result != false && respond_to_without_attributes?(method) - result = send(method) - end + def valid_with_callbacks? #:nodoc: + @_on_validate = new_record? ? :create : :update + _run_validation_callbacks do + valid_without_callbacks? + end + end - notify_observers(method) + def destroy_with_callbacks #:nodoc: + _run_destroy_callbacks do + destroy_without_callbacks + end + end - return result + def deprecated_callback_method(symbol) #:nodoc: + if respond_to?(symbol) + ActiveSupport::Deprecation.warn("Base##{symbol} has been deprecated, please use Base.#{symbol} :method instead") + send(symbol) end + end end end diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb index a34ff4a47a..4e05b819b5 100644 --- a/activerecord/lib/active_record/observer.rb +++ b/activerecord/lib/active_record/observer.rb @@ -1,6 +1,3 @@ -require 'singleton' -require 'set' - module ActiveRecord # Observer classes respond to lifecycle callbacks to implement trigger-like # behavior outside the original class. This is a great way to reduce the @@ -88,11 +85,17 @@ module ActiveRecord # singletons and that call instantiates and registers them. # class Observer < ActiveModel::Observer + extlib_inheritable_accessor(:observed_methods){ [] } + def initialize super observed_subclasses.each { |klass| add_observer!(klass) } end + def self.method_added(method) + observed_methods << method if ActiveRecord::Callbacks::CALLBACKS.include?(method.to_sym) + end + protected def observed_subclasses observed_classes.sum([]) { |klass| klass.send(:subclasses) } @@ -100,8 +103,15 @@ module ActiveRecord def add_observer!(klass) super - if respond_to?(:after_find) && !klass.method_defined?(:after_find) - klass.class_eval 'def after_find() end' + + # Check if a notifier callback was already added to the given class. If + # it was not, add it. + self.observed_methods.each do |method| + callback = :"_notify_observers_for_#{method}" + if (klass.instance_methods & [callback, callback.to_s]).empty? + klass.class_eval "def #{callback}; notify_observers(:#{method}); end" + klass.send(method, callback) + end end end end diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 5fc41cf054..ab79b520a2 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -110,8 +110,6 @@ module ActiveRecord included do alias_method_chain :save, :validation alias_method_chain :save!, :validation - - define_callbacks :validate_on_create, :validate_on_update end module ClassMethods @@ -127,17 +125,6 @@ module ActiveRecord object end end - - def validation_method(on) - case on - when :create - :validate_on_create - when :update - :validate_on_update - else - :validate - end - end end module InstanceMethods @@ -165,27 +152,15 @@ module ActiveRecord def valid? errors.clear - run_callbacks(:validate) + @_on_validate = new_record? ? :create : :update + _run_validate_callbacks - if respond_to?(:validate) - ActiveSupport::Deprecation.warn("Base#validate has been deprecated, please use Base.validate :method instead") - validate - end + deprecated_callback_method(:validate) if new_record? - run_callbacks(:validate_on_create) - - if respond_to?(:validate_on_create) - ActiveSupport::Deprecation.warn("Base#validate_on_create has been deprecated, please use Base.validate_on_create :method instead") - validate_on_create - end + deprecated_callback_method(:validate_on_create) else - run_callbacks(:validate_on_update) - - if respond_to?(:validate_on_update) - ActiveSupport::Deprecation.warn("Base#validate_on_update has been deprecated, please use Base.validate_on_update :method instead") - validate_on_update - end + deprecated_callback_method(:validate_on_update) end errors.empty? -- cgit v1.2.3 From 2ea1d684d93bd59887a9fd12e647941f0d1f4868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 8 Sep 2009 10:22:45 -0500 Subject: Refactor new callbacks and AR implementation. Signed-off-by: Joshua Peek --- activerecord/lib/active_record/callbacks.rb | 79 ++++++++--------------------- 1 file changed, 20 insertions(+), 59 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 361c7b2ef4..40a25811c4 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -214,8 +214,9 @@ module ActiveRecord CALLBACKS = [ :after_initialize, :after_find, :before_validation, :after_validation, - :before_save, :after_save, :before_create, :after_create, :before_update, - :after_update, :before_destroy, :after_destroy + :before_save, :around_save, :after_save, :before_create, :around_create, + :after_create, :before_update, :around_update, :after_update, + :before_destroy, :around_destroy, :after_destroy ] included do @@ -223,7 +224,8 @@ module ActiveRecord alias_method_chain method, :callbacks end - define_callbacks :initialize, :find, :save, :create, :update, :destroy, :validation, "result == false" + define_callbacks :initialize, :find, :save, :create, :update, :destroy, + :validation, :terminator => "result == false", :scope => [:kind, :name] end module ClassMethods @@ -239,64 +241,23 @@ module ActiveRecord set_callback(:find, :after, *(args << options), &block) end - def before_save(*args, &block) - set_callback(:save, :before, *args, &block) - end - - def around_save(*args, &block) - set_callback(:save, :around, *args, &block) - end - - def after_save(*args, &block) - options = args.extract_options! - options[:prepend] = true - options[:if] = Array(options[:if]) << "!halted && value != false" - set_callback(:save, :after, *(args << options), &block) - end - - def before_create(*args, &block) - set_callback(:create, :before, *args, &block) - end - - def around_create(*args, &block) - set_callback(:create, :around, *args, &block) - end - - def after_create(*args, &block) - options = args.extract_options! - options[:prepend] = true - options[:if] = Array(options[:if]) << "!halted && value != false" - set_callback(:create, :after, *(args << options), &block) - end - - def before_update(*args, &block) - set_callback(:update, :before, *args, &block) - end - - def around_update(*args, &block) - set_callback(:update, :around, *args, &block) - end - - def after_update(*args, &block) - options = args.extract_options! - options[:prepend] = true - options[:if] = Array(options[:if]) << "!halted && value != false" - set_callback(:update, :after, *(args << options), &block) - end + [:save, :create, :update, :destroy].each do |callback| + module_eval <<-CALLBACKS, __FILE__, __LINE__ + def before_#{callback}(*args, &block) + set_callback(:#{callback}, :before, *args, &block) + end - def before_destroy(*args, &block) - set_callback(:destroy, :before, *args, &block) - end + def around_#{callback}(*args, &block) + set_callback(:#{callback}, :around, *args, &block) + end - def around_destroy(*args, &block) - set_callback(:destroy, :around, *args, &block) - end - - def after_destroy(*args, &block) - options = args.extract_options! - options[:prepend] = true - options[:if] = Array(options[:if]) << "!halted && value != false" - set_callback(:destroy, :after, *(args << options), &block) + def after_#{callback}(*args, &block) + options = args.extract_options! + options[:prepend] = true + options[:if] = Array(options[:if]) << "!halted && value != false" + set_callback(:#{callback}, :after, *(args << options), &block) + end + CALLBACKS end def before_validation(*args, &block) -- cgit v1.2.3 From ff2eb2d8085f138acc6815690b519c30e458513b Mon Sep 17 00:00:00 2001 From: Shugo Maeda Date: Fri, 11 Sep 2009 13:42:46 +0900 Subject: Removed the copyright notice not to show it in the result of 'ri ActiveRecord'. --- .../lib/active_record/locking/pessimistic.rb | 22 ---------------------- 1 file changed, 22 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb index 320659596f..fcc9ebb4af 100644 --- a/activerecord/lib/active_record/locking/pessimistic.rb +++ b/activerecord/lib/active_record/locking/pessimistic.rb @@ -1,25 +1,3 @@ -# Copyright (c) 2006 Shugo Maeda -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject -# to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - module ActiveRecord module Locking # Locking::Pessimistic provides support for row-level locking using -- cgit v1.2.3 From 8682d76cc988715fdea11e2c88fa2b56ae2b4709 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 11 Sep 2009 19:22:54 -0700 Subject: Revert "Allow frameworks to be required by their gem name" This has just been confusing. Better to educate than band-aid. This reverts commit 18a24274ec823ded4ffa29bf33fd3d76816aab7e. Originally from http://dev.rubyonrails.org/ticket/8845 [drnic] --- activerecord/lib/activerecord.rb | 1 - 1 file changed, 1 deletion(-) delete mode 100644 activerecord/lib/activerecord.rb (limited to 'activerecord/lib') diff --git a/activerecord/lib/activerecord.rb b/activerecord/lib/activerecord.rb deleted file mode 100644 index cd62b2afdc..0000000000 --- a/activerecord/lib/activerecord.rb +++ /dev/null @@ -1 +0,0 @@ -require 'active_record' -- cgit v1.2.3 From 3180619c0d228812c119e9704ac5956cbcad8614 Mon Sep 17 00:00:00 2001 From: sdsykes Date: Fri, 11 Sep 2009 12:53:57 +0300 Subject: Fix habtm associations when using multiple databases [#3128] Signed-off-by: Jeremy Kemper --- .../active_record/associations/has_and_belongs_to_many_association.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index d91c555dad..417e2fdc0f 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -24,8 +24,8 @@ module ActiveRecord def has_primary_key? return @has_primary_key unless @has_primary_key.nil? - @has_primary_key = (ActiveRecord::Base.connection.supports_primary_key? && - ActiveRecord::Base.connection.primary_key(@reflection.options[:join_table])) + @has_primary_key = (@owner.connection.supports_primary_key? && + @owner.connection.primary_key(@reflection.options[:join_table])) end protected -- cgit v1.2.3 From bcd0ef710ec6d2cc6b880c39de0dfacc07df85e4 Mon Sep 17 00:00:00 2001 From: Mike Breen Date: Sat, 11 Jul 2009 14:30:35 +0200 Subject: Raise an exception with friendlier error message when attempting to build a polymorphic belongs_to with accepts_nested_attributes_for. [#2318 state:resolved] Signed-off-by: Eloy Duran --- activerecord/lib/active_record/nested_attributes.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index bc4cca7855..0def6d5c89 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -260,7 +260,12 @@ module ActiveRecord if attributes['id'].blank? unless reject_new_record?(association_name, attributes) - send("build_#{association_name}", attributes.except(*UNASSIGNABLE_KEYS)) + method = "build_#{association_name}" + if respond_to?(method) + send(method, attributes.except(*UNASSIGNABLE_KEYS)) + else + raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?" + end end elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy) -- cgit v1.2.3 From a44a1257d879311d88c2d10c366ab0d6561f903a Mon Sep 17 00:00:00 2001 From: Lance Ivy Date: Sat, 11 Jul 2009 15:09:09 +0200 Subject: Don't cascade autosave validation to destroyed children. [#2761 state:resolved] Signed-off-by: Eloy Duran --- activerecord/lib/active_record/autosave_association.rb | 2 ++ activerecord/lib/active_record/base.rb | 5 +++++ 2 files changed, 7 insertions(+) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index c1bc8423a9..ebd47ec634 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -245,6 +245,8 @@ module ActiveRecord # the parent, self, if it wasn't. Skips any :autosave # enabled records if they're marked_for_destruction?. def association_valid?(reflection, association) + return true if association.destroyed? + unless valid = association.valid? if reflection.options[:autosave] unless association.marked_for_destruction? diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index afa4185c60..2f6e3e8ffd 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2813,6 +2813,11 @@ module ActiveRecord #:nodoc: @attributes.frozen? end + # Returns +true+ if the record has been destroyed. + def destroyed? + @destroyed + end + # Returns duplicated record with unfreezed attributes. def dup obj = super -- cgit v1.2.3 From 6cc0b9638fbb6ede3c46b51d7dab17881416014c Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sat, 11 Jul 2009 17:52:13 +0200 Subject: Explicitely setting `autosave => false' should override new_record autosaving. [#2214 state:resolved] Original author is Jacob. --- activerecord/lib/active_record/autosave_association.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index ebd47ec634..aff29dcc4e 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -285,7 +285,7 @@ module ActiveRecord records.each do |record| if autosave && record.marked_for_destruction? association.destroy(record) - elsif @new_record_before_save || record.new_record? + elsif autosave != false && (@new_record_before_save || record.new_record?) if autosave association.send(:insert_record, record, false, false) else @@ -316,7 +316,7 @@ module ActiveRecord if autosave && association.marked_for_destruction? association.destroy - elsif new_record? || association.new_record? || association[reflection.primary_key_name] != id || autosave + elsif autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != id || autosave) association[reflection.primary_key_name] = id association.save(!autosave) end @@ -337,7 +337,7 @@ module ActiveRecord if autosave && association.marked_for_destruction? association.destroy - else + elsif autosave != false association.save(!autosave) if association.new_record? || autosave if association.updated? -- cgit v1.2.3 From 845f62f4730fb9ab8847033f9ab7435c40006662 Mon Sep 17 00:00:00 2001 From: Dmitry Polushkin Date: Sat, 11 Jul 2009 18:46:11 +0200 Subject: Fix autosave association to skip validation if it is marked for destruction. [#2064 state:resolved] Signed-off-by: Eloy Duran --- activerecord/lib/active_record/autosave_association.rb | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index aff29dcc4e..10dd0b4f05 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -243,17 +243,15 @@ module ActiveRecord # Returns whether or not the association is valid and applies any errors to # the parent, self, if it wasn't. Skips any :autosave - # enabled records if they're marked_for_destruction?. + # enabled records if they're marked_for_destruction? or destroyed. def association_valid?(reflection, association) - return true if association.destroyed? + return true if association.destroyed? || association.marked_for_destruction? unless valid = association.valid? if reflection.options[:autosave] - unless association.marked_for_destruction? - association.errors.each do |attribute, message| - attribute = "#{reflection.name}_#{attribute}" - errors[attribute] << message if errors[attribute].empty? - end + association.errors.each do |attribute, message| + attribute = "#{reflection.name}_#{attribute}" + errors[attribute] << message if errors[attribute].empty? end else errors.add(reflection.name) -- cgit v1.2.3 From 3091252abaafd15bc085f0be2b17829bebb6522c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sat, 11 Jul 2009 19:01:21 +0200 Subject: Rename nested attributes _delete to _destroy to reflect its actual behavior and DSL (:allow_destroy). Deprecation warning added. [#2889 state:resolved] Signed-off-by: Eloy Duran --- .../lib/active_record/nested_attributes.rb | 53 +++++++++++++--------- 1 file changed, 32 insertions(+), 21 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 0def6d5c89..3c8140816c 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -66,10 +66,10 @@ module ActiveRecord # accepts_nested_attributes_for :avatar, :allow_destroy => true # end # - # Now, when you add the _delete key to the attributes hash, with a + # Now, when you add the _destroy key to the attributes hash, with a # value that evaluates to +true+, you will destroy the associated model: # - # member.avatar_attributes = { :id => '2', :_delete => '1' } + # member.avatar_attributes = { :id => '2', :_destroy => '1' } # member.avatar.marked_for_destruction? # => true # member.save # member.avatar #=> nil @@ -89,14 +89,14 @@ module ActiveRecord # the attribute hash. # # For each hash that does _not_ have an id key a new record will - # be instantiated, unless the hash also contains a _delete key + # be instantiated, unless the hash also contains a _destroy key # that evaluates to +true+. # # params = { :member => { # :name => 'joe', :posts_attributes => [ # { :title => 'Kari, the awesome Ruby documentation browser!' }, # { :title => 'The egalitarian assumption of the modern citizen' }, - # { :title => '', :_delete => '1' } # this will be ignored + # { :title => '', :_destroy => '1' } # this will be ignored # ] # }} # @@ -144,7 +144,7 @@ module ActiveRecord # By default the associated records are protected from being destroyed. If # you want to destroy any of the associated records through the attributes # hash, you have to enable it first using the :allow_destroy - # option. This will allow you to also use the _delete key to + # option. This will allow you to also use the _destroy key to # destroy existing records: # # class Member < ActiveRecord::Base @@ -153,7 +153,7 @@ module ActiveRecord # end # # params = { :member => { - # :posts_attributes => [{ :id => '2', :_delete => '1' }] + # :posts_attributes => [{ :id => '2', :_destroy => '1' }] # }} # # member.attributes = params['member'] @@ -176,14 +176,14 @@ module ActiveRecord # Supported options: # [:allow_destroy] # If true, destroys any members from the attributes hash with a - # _delete key and a value that evaluates to +true+ + # _destroy key and a value that evaluates to +true+ # (eg. 1, '1', true, or 'true'). This option is off by default. # [:reject_if] # Allows you to specify a Proc that checks whether a record should be # built for a certain attribute hash. The hash is passed to the Proc # and the Proc should return either +true+ or +false+. When no Proc # is specified a record will be built for all attribute hashes that - # do not have a _delete that evaluates to true. + # do not have a _destroy value that evaluates to true. # Passing :all_blank instead of a Proc will create a proc # that will reject a record where all the attributes are blank. # @@ -236,15 +236,25 @@ module ActiveRecord # destruction of this association. # # See ActionView::Helpers::FormHelper::fields_for for more info. - def _delete + def _destroy marked_for_destruction? end + # Deal with deprecated _delete. + # + def _delete #:nodoc: + ActiveSupport::Deprecation.warn "_delete is deprecated in nested attributes. Use _destroy instead." + _destroy + end + private # Attribute hash keys that should not be assigned as normal attributes. # These hash keys are nested attributes implementation details. - UNASSIGNABLE_KEYS = %w{ id _delete } + # + # TODO Remove _delete from UNASSIGNABLE_KEYS when deprecation warning are + # removed. + UNASSIGNABLE_KEYS = %w( id _destroy _delete ) # Assigns the given attributes to the association. # @@ -253,7 +263,7 @@ module ActiveRecord # record will be built. # # If the given attributes include a matching :id attribute _and_ a - # :_delete key set to a truthy value, then the existing record + # :_destroy key set to a truthy value, then the existing record # will be marked for destruction. def assign_nested_attributes_for_one_to_one_association(association_name, attributes, allow_destroy) attributes = attributes.stringify_keys @@ -277,7 +287,7 @@ module ActiveRecord # Hashes with an :id value matching an existing associated record # will update that record. Hashes without an :id value will build # a new record for the association. Hashes with a matching :id - # value and a :_delete key set to a truthy value will mark the + # value and a :_destroy key set to a truthy value will mark the # matched record for destruction. # # For example: @@ -285,7 +295,7 @@ module ActiveRecord # assign_nested_attributes_for_collection_association(:people, { # '1' => { :id => '1', :name => 'Peter' }, # '2' => { :name => 'John' }, - # '3' => { :id => '2', :_delete => true } + # '3' => { :id => '2', :_destroy => true } # }) # # Will update the name of the Person with ID 1, build a new associated @@ -297,7 +307,7 @@ module ActiveRecord # assign_nested_attributes_for_collection_association(:people, [ # { :id => '1', :name => 'Peter' }, # { :name => 'John' }, - # { :id => '2', :_delete => true } + # { :id => '2', :_destroy => true } # ]) def assign_nested_attributes_for_collection_association(association_name, attributes_collection, allow_destroy) unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array) @@ -322,25 +332,26 @@ module ActiveRecord end # Updates a record with the +attributes+ or marks it for destruction if - # +allow_destroy+ is +true+ and has_delete_flag? returns +true+. + # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+. def assign_to_or_mark_for_destruction(record, attributes, allow_destroy) - if has_delete_flag?(attributes) && allow_destroy + if has_destroy_flag?(attributes) && allow_destroy record.mark_for_destruction else record.attributes = attributes.except(*UNASSIGNABLE_KEYS) end end - # Determines if a hash contains a truthy _delete key. - def has_delete_flag?(hash) - ConnectionAdapters::Column.value_to_boolean hash['_delete'] + # Determines if a hash contains a truthy _destroy key. + def has_destroy_flag?(hash) + ConnectionAdapters::Column.value_to_boolean(hash['_destroy']) || + ConnectionAdapters::Column.value_to_boolean(hash['_delete']) # TODO Remove after deprecation. end # Determines if a new record should be build by checking for - # has_delete_flag? or if a :reject_if proc exists for this + # has_destroy_flag? or if a :reject_if proc exists for this # association and evaluates to +true+. def reject_new_record?(association_name, attributes) - has_delete_flag?(attributes) || + has_destroy_flag?(attributes) || self.class.reject_new_nested_attributes_procs[association_name].try(:call, attributes) end end -- cgit v1.2.3 From c01be9de322ba846923340e41e69821d01541610 Mon Sep 17 00:00:00 2001 From: Graeme Porteous Date: Sat, 11 Jul 2009 20:04:18 +0200 Subject: Fix has_one with foreign_key and primary_key association bug which caused the associated object being lost when saving the owner. [#1756 state:resolved] Mixed in a bit from patch by ransom-briggs. [#2813 state:resolved] Signed-off-by: Eloy Duran --- activerecord/lib/active_record/autosave_association.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 10dd0b4f05..75c49ecb2b 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -314,9 +314,12 @@ module ActiveRecord if autosave && association.marked_for_destruction? association.destroy - elsif autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != id || autosave) - association[reflection.primary_key_name] = id - association.save(!autosave) + else + key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id + if autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != key || autosave) + association[reflection.primary_key_name] = key + association.save(!autosave) + end end end end -- cgit v1.2.3 From 65f98951ac5fe75191c6fde996b9e0f9b765414f Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sat, 11 Jul 2009 20:52:03 +0200 Subject: During autosave, ignore records that already have been destroyed. [#2537 state:resolved] --- activerecord/lib/active_record/autosave_association.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 75c49ecb2b..bfae5933ea 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -281,6 +281,8 @@ module ActiveRecord if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) records.each do |record| + next if record.destroyed? + if autosave && record.marked_for_destruction? association.destroy(record) elsif autosave != false && (@new_record_before_save || record.new_record?) @@ -309,7 +311,7 @@ module ActiveRecord # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_has_one_association(reflection) - if (association = association_instance_get(reflection.name)) && !association.target.nil? + if (association = association_instance_get(reflection.name)) && !association.target.nil? && !association.destroyed? autosave = reflection.options[:autosave] if autosave && association.marked_for_destruction? @@ -333,7 +335,7 @@ module ActiveRecord # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_belongs_to_association(reflection) - if association = association_instance_get(reflection.name) + if (association = association_instance_get(reflection.name)) && !association.destroyed? autosave = reflection.options[:autosave] if autosave && association.marked_for_destruction? -- cgit v1.2.3 From 580ec0dccde075330abe68eb13badb03b225f9b4 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sat, 11 Jul 2009 21:01:56 +0200 Subject: Added some documentation about setting :autosave => false on an association. --- activerecord/lib/active_record/associations.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 72061a1b31..266a52d612 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -280,9 +280,10 @@ module ActiveRecord # You can manipulate objects and associations before they are saved to the database, but there is some special behavior you should be # aware of, mostly involving the saving of associated objects. # - # Unless you enable the :autosave option on a has_one, belongs_to, - # has_many, or has_and_belongs_to_many association, - # in which case the members are always saved. + # Unless you set the :autosave option on a has_one, belongs_to, + # has_many, or has_and_belongs_to_many association. Setting it + # to +true+ will _always_ save the members, whereas setting it to +false+ will + # _never_ save the members. # # === One-to-one associations # -- cgit v1.2.3 From 938c0ee0455b8e784a771ce31631d9ec376ee6ab Mon Sep 17 00:00:00 2001 From: Alexey Kovyrin Date: Sat, 12 Sep 2009 14:55:34 +0200 Subject: Define autosave association validation methods only when needed. [#3161 state:resolved] Signed-off-by: Eloy Duran --- activerecord/lib/active_record/autosave_association.rb | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index bfae5933ea..7b5bd33863 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -158,7 +158,7 @@ module ActiveRecord def add_autosave_association_callbacks(reflection) save_method = "autosave_associated_records_for_#{reflection.name}" validation_method = "validate_associated_records_for_#{reflection.name}" - validate validation_method + force_validation = (reflection.options[:validate] == true || reflection.options[:autosave] == true) case reflection.macro when :has_many, :has_and_belongs_to_many @@ -169,7 +169,10 @@ module ActiveRecord after_create save_method after_update save_method - define_method(validation_method) { validate_collection_association(reflection) } + if force_validation || (reflection.macro == :has_many && reflection.options[:validate] != false) + define_method(validation_method) { validate_collection_association(reflection) } + validate validation_method + end else case reflection.macro when :has_one @@ -179,7 +182,11 @@ module ActiveRecord define_method(save_method) { save_belongs_to_association(reflection) } before_save save_method end - define_method(validation_method) { validate_single_association(reflection) } + + if force_validation + define_method(validation_method) { validate_single_association(reflection) } + validate validation_method + end end end end -- cgit v1.2.3 From a144b41cbc5111e6282674930e660a7a29578d0a Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sat, 12 Sep 2009 15:03:05 +0200 Subject: Removed some superfluous conditionals from the autosave association validation methods. Which are unneeded now that we only define them when needed. --- activerecord/lib/active_record/autosave_association.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 7b5bd33863..8f37fcd515 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -230,10 +230,8 @@ module ActiveRecord # Validate the association if :validate or :autosave is # turned on for the association specified by +reflection+. def validate_single_association(reflection) - if reflection.options[:validate] == true || reflection.options[:autosave] == true - if (association = association_instance_get(reflection.name)) && !association.target.nil? - association_valid?(reflection, association) - end + if (association = association_instance_get(reflection.name)) && !association.target.nil? + association_valid?(reflection, association) end end @@ -241,7 +239,7 @@ module ActiveRecord # :autosave is turned on for the association specified by # +reflection+. def validate_collection_association(reflection) - if reflection.options[:validate] != false && association = association_instance_get(reflection.name) + 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) } end -- cgit v1.2.3 From 26639e8a4558a844e2e374b2916545c3e717b387 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sat, 12 Sep 2009 16:16:48 +0200 Subject: Removed the version of ActiveRecord::Base#destroyed? that was added in a44a1257d879311d88c2d10c366ab0d6561f903a. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Because José Valim was cheeky enough to already add it to the master branch. --- activerecord/lib/active_record/base.rb | 5 ----- 1 file changed, 5 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 2f6e3e8ffd..afa4185c60 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2813,11 +2813,6 @@ module ActiveRecord #:nodoc: @attributes.frozen? end - # Returns +true+ if the record has been destroyed. - def destroyed? - @destroyed - end - # Returns duplicated record with unfreezed attributes. def dup obj = super -- cgit v1.2.3 From dbe9fa03dfce54eb2b27341eed924b95e6afbdea Mon Sep 17 00:00:00 2001 From: sdsykes Date: Mon, 7 Sep 2009 13:22:19 +0300 Subject: Ruby 1.9 compat: corrected instance_methods check [#3156 state:committed] Signed-off-by: Jeremy Kemper --- activerecord/lib/active_record/connection_adapters/mysql_adapter.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 4edb64c2c0..1bb1c0bc15 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -8,7 +8,8 @@ module MysqlCompat #:nodoc: raise 'Mysql not loaded' unless defined?(::Mysql) target = defined?(Mysql::Result) ? Mysql::Result : MysqlRes - return if target.instance_methods.include?('all_hashes') + return if target.instance_methods.include?('all_hashes') || + target.instance_methods.include?(:all_hashes) # Ruby driver has a version string and returns null values in each_hash # C driver >= 2.7 returns null values in each_hash -- cgit v1.2.3 From c9d3c48dc6389feb2001372cd76e96274e773c9b Mon Sep 17 00:00:00 2001 From: Justin Bailey Date: Mon, 14 Sep 2009 17:53:04 -0700 Subject: Enable use of MySQL stored procedures by default. [#3204 state:committed] Signed-off-by: Jeremy Kemper --- activerecord/lib/active_record/connection_adapters/mysql_adapter.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 1bb1c0bc15..1072eb7ac1 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -65,12 +65,15 @@ module ActiveRecord raise end end + MysqlCompat.define_all_hashes_method! mysql = Mysql.init mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey] - ConnectionAdapters::MysqlAdapter.new(mysql, logger, [host, username, password, database, port, socket], config) + default_flags = Mysql.const_defined?(:CLIENT_MULTI_RESULTS) ? Mysql::CLIENT_MULTI_RESULTS : 0 + options = [host, username, password, database, port, socket, default_flags] + ConnectionAdapters::MysqlAdapter.new(mysql, logger, options, config) end end -- cgit v1.2.3 From 7701c6f1c012abb09cd61d3092fbb40fc77aeb6d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 17 Sep 2009 16:15:04 -0700 Subject: Collapse nested conditional --- activerecord/lib/active_record/base.rb | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index afa4185c60..1adab2e832 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1654,22 +1654,20 @@ module ActiveRecord #:nodoc: if subclass_name.empty? allocate - else - # Ignore type if no column is present since it was probably - # pulled in from a sloppy join. - unless columns_hash.include?(inheritance_column) - allocate + # Ignore type if no column is present since it was probably + # pulled in from a sloppy join. + elsif !columns_hash.include?(inheritance_column) + allocate - else - begin - compute_type(subclass_name).allocate - rescue NameError - raise SubclassNotFound, - "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " + - "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + - "Please rename this column if you didn't intend it to be used for storing the inheritance class " + - "or overwrite #{self.to_s}.inheritance_column to use another column for that information." - end + else + begin + compute_type(subclass_name).allocate + rescue NameError + raise SubclassNotFound, + "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " + + "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + + "Please rename this column if you didn't intend it to be used for storing the inheritance class " + + "or overwrite #{self.to_s}.inheritance_column to use another column for that information." end end else -- cgit v1.2.3 From 3fc2d1ebd932428548961ce509c55fecc00f448e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 17 Sep 2009 17:26:29 -0700 Subject: Extract class-finder method from instantiate --- activerecord/lib/active_record/base.rb | 46 ++++++++++++++-------------------- 1 file changed, 19 insertions(+), 27 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 1adab2e832..502fe0442e 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1648,34 +1648,10 @@ module ActiveRecord #:nodoc: # single-table inheritance model that makes it possible to create # objects of different types from the same table. def instantiate(record) - object = - if subclass_name = record[inheritance_column] - # No type given. - if subclass_name.empty? - allocate + object = find_sti_class(record[inheritance_column]).allocate - # Ignore type if no column is present since it was probably - # pulled in from a sloppy join. - elsif !columns_hash.include?(inheritance_column) - allocate - - else - begin - compute_type(subclass_name).allocate - rescue NameError - raise SubclassNotFound, - "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " + - "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + - "Please rename this column if you didn't intend it to be used for storing the inheritance class " + - "or overwrite #{self.to_s}.inheritance_column to use another column for that information." - end - end - else - allocate - end - - object.instance_variable_set("@attributes", record) - object.instance_variable_set("@attributes_cache", Hash.new) + object.instance_variable_set(:'@attributes', record) + object.instance_variable_set(:'@attributes_cache', {}) object.send(:_run_find_callbacks) object.send(:_run_initialize_callbacks) @@ -1683,6 +1659,22 @@ module ActiveRecord #:nodoc: object end + def find_sti_class(type_name) + if type_name.blank? || !columns_hash.include?(inheritance_column) + self + else + begin + compute_type(type_name) + rescue NameError + raise SubclassNotFound, + "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " + + "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + + "Please rename this column if you didn't intend it to be used for storing the inheritance class " + + "or overwrite #{name}.inheritance_column to use another column for that information." + end + end + end + # Nest the type name in the same module as this class. # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo def type_name_with_module(type_name) -- cgit v1.2.3 From 8f47f311b7665d74220baf1449b39dc4e70e13e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 18 Sep 2009 08:08:02 -0300 Subject: Instrument process_action, render and sql. --- .../connection_adapters/abstract_adapter.rb | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index fab70f34b9..78c7a4b697 100755 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -201,16 +201,12 @@ module ActiveRecord protected def log(sql, name) - if block_given? - result = nil - ms = Benchmark.ms { result = yield } - @runtime += ms - log_info(sql, name, ms) - result - else - log_info(sql, name, 0) - nil + event = ActiveSupport::Orchestra.instrument(:sql, :sql => sql, :name => name) do + yield if block_given? end + @runtime += event.duration + log_info(sql, name, event.duration) + event.result rescue Exception => e # Log message and raise exception. # Set last_verification to 0, so that connection gets verified @@ -221,10 +217,10 @@ module ActiveRecord raise translate_exception(e, message) end - def translate_exception(e, message) - # override in derived class - ActiveRecord::StatementInvalid.new(message) - end + def translate_exception(e, message) + # override in derived class + ActiveRecord::StatementInvalid.new(message) + end def format_log_entry(message, dump = nil) if ActiveRecord::Base.colorize_logging -- cgit v1.2.3