diff options
author | Ryuta Kamizono <kamipo@gmail.com> | 2019-04-25 03:32:36 +0900 |
---|---|---|
committer | Ryuta Kamizono <kamipo@gmail.com> | 2019-04-25 03:32:36 +0900 |
commit | 186458753f3614623523ad079d92c537cf03cb4a (patch) | |
tree | 5e75374e3289543940d05735b4e3a4373abc4c6c /activerecord/lib/active_record/associations | |
parent | 3a4aa492560d311f8d549f739bd69945f5d508ea (diff) | |
parent | 3fe83d1dd99ac2662852da0dcfe7e91dc08ae160 (diff) | |
download | rails-186458753f3614623523ad079d92c537cf03cb4a.tar.gz rails-186458753f3614623523ad079d92c537cf03cb4a.tar.bz2 rails-186458753f3614623523ad079d92c537cf03cb4a.zip |
Merge pull request #35869 from abhaynikam/35866-add-touch-option-for-has-one-association
Adds missing touch option to has_one association
Diffstat (limited to 'activerecord/lib/active_record/associations')
-rw-r--r-- | activerecord/lib/active_record/associations/builder/has_one.rb | 36 |
1 files changed, 34 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb index a17cfcb805..27ebe8cb71 100644 --- a/activerecord/lib/active_record/associations/builder/has_one.rb +++ b/activerecord/lib/active_record/associations/builder/has_one.rb @@ -7,7 +7,7 @@ module ActiveRecord::Associations::Builder # :nodoc: end def self.valid_options(options) - valid = super + [:as] + valid = super + [:as, :touch] valid += [:through, :source, :source_type] if options[:through] valid end @@ -16,6 +16,11 @@ module ActiveRecord::Associations::Builder # :nodoc: [:destroy, :delete, :nullify, :restrict_with_error, :restrict_with_exception] end + def self.define_callbacks(model, reflection) + super + add_touch_callbacks(model, reflection) if reflection.options[:touch] + end + def self.add_destroy_callbacks(model, reflection) super unless reflection.options[:through] end @@ -27,6 +32,33 @@ module ActiveRecord::Associations::Builder # :nodoc: end end - private_class_method :macro, :valid_options, :valid_dependent_options, :add_destroy_callbacks, :define_validations + def self.touch_record(o, name, touch) + record = o.send name + + return unless record && record.persisted? + + if touch != true + record.touch(touch) + else + record.touch + end + end + + def self.add_touch_callbacks(model, reflection) + name = reflection.name + touch = reflection.options[:touch] + + callback = lambda { |record| + HasOne.touch_record(record, name, touch) + } + + model.after_create callback, if: :saved_changes? + model.after_update callback, if: :saved_changes? + model.after_destroy callback + model.after_touch callback + end + + private_class_method :macro, :valid_options, :valid_dependent_options, :add_destroy_callbacks, + :define_callbacks, :define_validations, :add_touch_callbacks end end |