aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record
diff options
context:
space:
mode:
authorAbhay Nikam <nikam.abhay1@gmail.com>2019-04-05 10:14:30 +0530
committerRyuta Kamizono <kamipo@gmail.com>2019-04-25 03:31:34 +0900
commit3fe83d1dd99ac2662852da0dcfe7e91dc08ae160 (patch)
tree91da5f37d437e10155089ae36348ca5f25a5a4e8 /activerecord/lib/active_record
parentaa5e6b590595f76b8c215483aa539503821ac3ff (diff)
downloadrails-3fe83d1dd99ac2662852da0dcfe7e91dc08ae160.tar.gz
rails-3fe83d1dd99ac2662852da0dcfe7e91dc08ae160.tar.bz2
rails-3fe83d1dd99ac2662852da0dcfe7e91dc08ae160.zip
Adds touch option to has_one association
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r--activerecord/lib/active_record/associations/builder/has_one.rb36
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