From ec8f04584479aff895b0b511a7ba1e9d33f84067 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sun, 1 Feb 2009 14:44:30 +1300 Subject: Add support for nested object forms to ActiveRecord and the helpers in ActionPack Signed-Off-By: Michael Koziarski [#1202 state:committed] --- .../lib/active_record/autosave_association.rb | 213 +++++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 activerecord/lib/active_record/autosave_association.rb (limited to 'activerecord/lib/active_record/autosave_association.rb') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb new file mode 100644 index 0000000000..07660ebd03 --- /dev/null +++ b/activerecord/lib/active_record/autosave_association.rb @@ -0,0 +1,213 @@ +module ActiveRecord + # AutosaveAssociation is a module that takes care of automatically saving + # your associations when the parent is saved. In addition to saving, it + # also destroys any associations that were marked for destruction. + # (See mark_for_destruction and marked_for_destruction?) + # + # Saving of the parent, its associations, and the destruction of marked + # associations, all happen inside 1 transaction. This should never leave the + # database in an inconsistent state after, for instance, mass assigning + # attributes and saving them. + # + # If validations for any of the associations fail, their error messages will + # be applied to the parent. + # + # Note that it also means that associations marked for destruction won't + # be destroyed directly. They will however still be marked for destruction. + # + # === One-to-one Example + # + # Consider a Post model with one Author: + # + # class Post + # has_one :author, :autosave => true + # end + # + # Saving changes to the parent and its associated model can now be performed + # automatically _and_ atomically: + # + # post = Post.find(1) + # post.title # => "The current global position of migrating ducks" + # post.author.name # => "alloy" + # + # post.title = "On the migration of ducks" + # post.author.name = "Eloy Duran" + # + # post.save + # post.reload + # post.title # => "On the migration of ducks" + # post.author.name # => "Eloy Duran" + # + # Destroying an associated model, as part of the parent's save action, is as + # simple as marking it for destruction: + # + # post.author.mark_for_destruction + # post.author.marked_for_destruction? # => true + # + # Note that the model is _not_ yet removed from the database: + # id = post.author.id + # Author.find_by_id(id).nil? # => false + # + # post.save + # post.reload.author # => nil + # + # Now it _is_ removed from the database: + # Author.find_by_id(id).nil? # => true + # + # === One-to-many Example + # + # Consider a Post model with many Comments: + # + # class Post + # has_many :comments, :autosave => true + # end + # + # Saving changes to the parent and its associated model can now be performed + # automatically _and_ atomically: + # + # post = Post.find(1) + # post.title # => "The current global position of migrating ducks" + # post.comments.first.body # => "Wow, awesome info thanks!" + # post.comments.last.body # => "Actually, your article should be named differently." + # + # post.title = "On the migration of ducks" + # post.comments.last.body = "Actually, your article should be named differently. [UPDATED]: You are right, thanks." + # + # post.save + # post.reload + # post.title # => "On the migration of ducks" + # post.comments.last.body # => "Actually, your article should be named differently. [UPDATED]: You are right, thanks." + # + # Destroying one of the associated models members, as part of the parent's + # save action, is as simple as marking it for destruction: + # + # post.comments.last.mark_for_destruction + # post.comments.last.marked_for_destruction? # => true + # post.comments.length # => 2 + # + # Note that the model is _not_ yet removed from the database: + # id = post.comments.last.id + # Comment.find_by_id(id).nil? # => false + # + # post.save + # post.reload.comments.length # => 1 + # + # Now it _is_ removed from the database: + # Comment.find_by_id(id).nil? # => true + # + # === Validation + # + # Validation is performed on the parent as usual, but also on all autosave + # enabled associations. If any of the associations fail validation, its + # error messages will be applied on the parents errors object and validation + # of the parent will fail. + # + # Consider a Post model with Author which validates the presence of its name + # attribute: + # + # class Post + # has_one :author, :autosave => true + # end + # + # class Author + # validates_presence_of :name + # end + # + # post = Post.find(1) + # post.author.name = '' + # post.save # => false + # post.errors # => #["can't be blank"]}, @base=#> + # + # No validations will be performed on the associated models when validations + # are skipped for the parent: + # + # post = Post.find(1) + # post.author.name = '' + # post.save(false) # => true + module AutosaveAssociation + def self.included(base) + base.class_eval do + alias_method_chain :reload, :autosave_associations + alias_method_chain :save, :autosave_associations + alias_method_chain :valid?, :autosave_associations + + %w{ has_one belongs_to has_many has_and_belongs_to_many }.each do |type| + base.send("valid_keys_for_#{type}_association") << :autosave + end + end + end + + # Saves the parent, self, and any loaded autosave associations. + # In addition, it destroys all children that were marked for destruction + # with mark_for_destruction. + # + # 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_with_autosave_associations(perform_validation = true) + returning(save_without_autosave_associations(perform_validation)) do |valid| + if valid + self.class.reflect_on_all_autosave_associations.each do |reflection| + if (association = association_instance_get(reflection.name)) && association.loaded? + if association.is_a?(Array) + association.proxy_target.each do |child| + child.marked_for_destruction? ? child.destroy : child.save(perform_validation) + end + else + association.marked_for_destruction? ? association.destroy : association.save(perform_validation) + end + end + end + end + end + end + + # Returns whether or not the parent, self, and any loaded autosave associations are valid. + def valid_with_autosave_associations? + if valid_without_autosave_associations? + self.class.reflect_on_all_autosave_associations.all? do |reflection| + if (association = association_instance_get(reflection.name)) && association.loaded? + if association.is_a?(Array) + association.proxy_target.all? { |child| autosave_association_valid?(reflection, child) } + else + autosave_association_valid?(reflection, association) + end + else + true # association not loaded yet, so it should be valid + end + end + else + false # self was not valid + end + end + + # Returns whether or not the association is valid and applies any errors to the parent, self, if it wasn't. + def autosave_association_valid?(reflection, association) + returning(association.valid?) do |valid| + association.errors.each do |attribute, message| + errors.add "#{reflection.name}_#{attribute}", message + end unless valid + end + end + + # Reloads the attributes of the object as usual and removes a mark for destruction. + def reload_with_autosave_associations(options = nil) + @marked_for_destruction = false + reload_without_autosave_associations(options) + end + + # Marks this record to be destroyed as part of the parents save transaction. + # This does _not_ actually destroy the record yet, rather it will be destroyed when parent.save is called. + # + # Only useful if the :autosave option on the parent is enabled for this associated model. + def mark_for_destruction + @marked_for_destruction = true + end + + # Returns whether or not this record will be destroyed as part of the parents save transaction. + # + # Only useful if the :autosave option on the parent is enabled for this associated model. + def marked_for_destruction? + @marked_for_destruction + end + end +end \ No newline at end of file -- cgit v1.2.3 From db5d6950169f8f10b6aec85faa2c38e0c57315c7 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Wed, 4 Feb 2009 21:40:53 +0100 Subject: Also save :autosave enabled associations when #save! is used. Signed-off-by: Michael Koziarski [#1877 state:committed] --- activerecord/lib/active_record/autosave_association.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'activerecord/lib/active_record/autosave_association.rb') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 07660ebd03..680b41518c 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -129,6 +129,7 @@ module ActiveRecord base.class_eval do alias_method_chain :reload, :autosave_associations alias_method_chain :save, :autosave_associations + alias_method_chain :save!, :autosave_associations alias_method_chain :valid?, :autosave_associations %w{ has_one belongs_to has_many has_and_belongs_to_many }.each do |type| @@ -161,6 +162,17 @@ module ActiveRecord end end + # Attempts to save the record just like save_with_autosave_associations but + # will raise a RecordInvalid exception instead of returning false if the + # record is not valid. + def save_with_autosave_associations! + if valid_with_autosave_associations? + save_with_autosave_associations(false) || raise(RecordNotSaved) + else + raise RecordInvalid.new(self) + end + end + # Returns whether or not the parent, self, and any loaded autosave associations are valid. def valid_with_autosave_associations? if valid_without_autosave_associations? -- cgit v1.2.3 From 5cda000bf0f6d85d1a1efedf9fa4d0b6eaf988a1 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 27 Feb 2009 13:50:24 +0100 Subject: Fixed that autosave should validate associations even if master is invalid [#1930 status:committed] --- .../lib/active_record/autosave_association.rb | 237 ++++++++++++++++----- 1 file changed, 179 insertions(+), 58 deletions(-) (limited to 'activerecord/lib/active_record/autosave_association.rb') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 680b41518c..6e09b13150 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -125,79 +125,63 @@ module ActiveRecord # post.author.name = '' # post.save(false) # => true module AutosaveAssociation + ASSOCIATION_TYPES = %w{ has_one belongs_to has_many has_and_belongs_to_many } + def self.included(base) base.class_eval do + base.extend(ClassMethods) alias_method_chain :reload, :autosave_associations - alias_method_chain :save, :autosave_associations - alias_method_chain :save!, :autosave_associations - alias_method_chain :valid?, :autosave_associations - %w{ has_one belongs_to has_many has_and_belongs_to_many }.each do |type| + ASSOCIATION_TYPES.each do |type| base.send("valid_keys_for_#{type}_association") << :autosave end end end - # Saves the parent, self, and any loaded autosave associations. - # In addition, it destroys all children that were marked for destruction - # with mark_for_destruction. - # - # 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_with_autosave_associations(perform_validation = true) - returning(save_without_autosave_associations(perform_validation)) do |valid| - if valid - self.class.reflect_on_all_autosave_associations.each do |reflection| - if (association = association_instance_get(reflection.name)) && association.loaded? - if association.is_a?(Array) - association.proxy_target.each do |child| - child.marked_for_destruction? ? child.destroy : child.save(perform_validation) - end - else - association.marked_for_destruction? ? association.destroy : association.save(perform_validation) - end - end + module ClassMethods + private + + # def belongs_to(name, options = {}) + # super + # add_autosave_association_callbacks(reflect_on_association(name)) + # end + ASSOCIATION_TYPES.each do |type| + module_eval %{ + def #{type}(name, options = {}) + super + add_autosave_association_callbacks(reflect_on_association(name)) end - end + } end - end - # Attempts to save the record just like save_with_autosave_associations but - # will raise a RecordInvalid exception instead of returning false if the - # record is not valid. - def save_with_autosave_associations! - if valid_with_autosave_associations? - save_with_autosave_associations(false) || raise(RecordNotSaved) - else - raise RecordInvalid.new(self) - end - end + # Adds a validate and save callback for the association as specified by + # the +reflection+. + 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 - # Returns whether or not the parent, self, and any loaded autosave associations are valid. - def valid_with_autosave_associations? - if valid_without_autosave_associations? - self.class.reflect_on_all_autosave_associations.all? do |reflection| - if (association = association_instance_get(reflection.name)) && association.loaded? - if association.is_a?(Array) - association.proxy_target.all? { |child| autosave_association_valid?(reflection, child) } - else - autosave_association_valid?(reflection, association) - end - else - true # association not loaded yet, so it should be valid + case reflection.macro + when :has_many, :has_and_belongs_to_many + before_save :before_save_collection_association + + define_method(save_method) { save_collection_association(reflection) } + # 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 + + define_method(validation_method) { validate_collection_association(reflection) } + else + case reflection.macro + when :has_one + define_method(save_method) { save_has_one_association(reflection) } + after_save save_method + when :belongs_to + define_method(save_method) { save_belongs_to_association(reflection) } + before_save save_method end + define_method(validation_method) { validate_single_association(reflection) } end - else - false # self was not valid - end - end - - # Returns whether or not the association is valid and applies any errors to the parent, self, if it wasn't. - def autosave_association_valid?(reflection, association) - returning(association.valid?) do |valid| - association.errors.each do |attribute, message| - errors.add "#{reflection.name}_#{attribute}", message - end unless valid end end @@ -221,5 +205,142 @@ module ActiveRecord def marked_for_destruction? @marked_for_destruction end + + private + + # Returns the record for an association collection that should be validated + # or saved. If +autosave+ is +false+ only new records will be returned, + # unless the parent is/was a new record itself. + def associated_records_to_validate_or_save(association, new_record, autosave) + if new_record + association + elsif association.loaded? + autosave ? association : association.select { |record| record.new_record? } + else + autosave ? association.target : association.target.select { |record| record.new_record? } + end + end + + # 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 + end + end + + # Validate the associated records if :validate or + # :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 records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave]) + records.each { |record| association_valid?(reflection, record) } + end + end + end + + # Returns whether or not the association is valid and applies any errors to + # the parent, self, if it wasn't. + def association_valid?(reflection, association) + unless valid = association.valid? + if reflection.options[:autosave] + association.errors.each do |attribute, message| + attribute = "#{reflection.name}_#{attribute}" + errors.add(attribute, message) unless errors.on(attribute) + end + else + errors.add(reflection.name) + end + end + valid + end + + # Is used as a before_save callback to check while saving a collection + # association whether or not the parent was a new record before saving. + def before_save_collection_association + @new_record_before_save = new_record? + true + end + + # Saves any new associated records, or all loaded autosave associations if + # :autosave is enabled on the association. + # + # In addition, it destroys all children that were marked for destruction + # with mark_for_destruction. + # + # 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_collection_association(reflection) + if association = association_instance_get(reflection.name) + autosave = reflection.options[:autosave] + + if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) + records.each do |record| + if autosave && record.marked_for_destruction? + record.destroy + elsif @new_record_before_save || record.new_record? + if autosave + association.send(:insert_record, record, false, false) + else + association.send(:insert_record, record) + end + elsif autosave + record.save(false) + end + end + end + + # reconstruct the SQL queries now that we know the owner's id + association.send(:construct_sql) if association.respond_to?(:construct_sql) + end + end + + # Saves the associated record if it's new or :autosave is enabled + # on the association. + # + # In addition, it will destroy the association if it was marked for + # destruction with mark_for_destruction. + # + # 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) + if reflection.options[:autosave] && association.marked_for_destruction? + association.destroy + elsif new_record? || association.new_record? || association[reflection.primary_key_name] != id || reflection.options[:autosave] + association[reflection.primary_key_name] = id + association.save(false) + end + end + end + + # Saves the associated record if it's new or :autosave is enabled + # on the association. + # + # In addition, it will destroy the association if it was marked for + # destruction with mark_for_destruction. + # + # 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 reflection.options[:autosave] && association.marked_for_destruction? + association.destroy + else + association.save(false) if association.new_record? || reflection.options[:autosave] + + if association.updated? + self[reflection.primary_key_name] = association.id + # TODO: Removing this code doesn't seem to matter… + if reflection.options[:polymorphic] + self[reflection.options[:foreign_type]] = association.class.base_class.name.to_s + end + end + end + end + end end end \ No newline at end of file -- cgit v1.2.3 From e2b925fa68203607fb4f9a9aa457c0435c969f9a Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Thu, 26 Feb 2009 11:56:27 +0100 Subject: Don't validate records of an :autosave association if they're marked for destruction. [#2064 status:resolved] Signed-off-by: David Heinemeier Hansson --- activerecord/lib/active_record/autosave_association.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'activerecord/lib/active_record/autosave_association.rb') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 6e09b13150..1c3d0567c1 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -243,13 +243,16 @@ module ActiveRecord end # Returns whether or not the association is valid and applies any errors to - # the parent, self, if it wasn't. + # the parent, self, if it wasn't. Skips any :autosave + # enabled records if they're marked_for_destruction?. def association_valid?(reflection, association) unless valid = association.valid? if reflection.options[:autosave] - association.errors.each do |attribute, message| - attribute = "#{reflection.name}_#{attribute}" - errors.add(attribute, message) unless errors.on(attribute) + unless association.marked_for_destruction? + association.errors.each do |attribute, message| + attribute = "#{reflection.name}_#{attribute}" + errors.add(attribute, message) unless errors.on(attribute) + end end else errors.add(reflection.name) -- cgit v1.2.3 From 92dadf6d7927fde1482ba1d96d0916093bfb83ca Mon Sep 17 00:00:00 2001 From: Will Bryant Date: Thu, 12 Mar 2009 02:13:26 +1300 Subject: Fixed autosave checks on objects with hm:t in :include [#2213 state:resolved] Signed-off-by: Pratik Naik --- activerecord/lib/active_record/autosave_association.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/autosave_association.rb') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 1c3d0567c1..6dcc5005d1 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -310,7 +310,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) + if (association = association_instance_get(reflection.name)) && !association.target.nil? if reflection.options[:autosave] && association.marked_for_destruction? association.destroy elsif new_record? || association.new_record? || association[reflection.primary_key_name] != id || reflection.options[:autosave] -- cgit v1.2.3 From 47bdf3bf40ec17e1f8ca1c0e3d7f697d0c4cd1bf Mon Sep 17 00:00:00 2001 From: Luca Guidi Date: Thu, 12 Mar 2009 15:24:37 +0000 Subject: Ensure AutosaveAssociation runs remove callbacks [#2146 state:resolved] Signed-off-by: Eloy Duran Signed-off-by: Pratik Naik --- activerecord/lib/active_record/autosave_association.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/autosave_association.rb') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 6dcc5005d1..741aa2acbe 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -283,7 +283,7 @@ module ActiveRecord if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) records.each do |record| if autosave && record.marked_for_destruction? - record.destroy + association.destroy(record) elsif @new_record_before_save || record.new_record? if autosave association.send(:insert_record, record, false, false) -- cgit v1.2.3