Created
June 6, 2012 10:09
-
-
Save mtgrosser/2881114 to your computer and use it in GitHub Desktop.
Classic behaviour of belongs_to :touch => true for Rails 3, using save! instead of update_all
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This snippet will provide a :nudge option for belongs_to associations, | |
# which behaves like the belongs_to :touch => true did in Rails 2.x. | |
# It will use save! instead of a sneaky update_all call, so all of your | |
# callbacks and validations will be invoked. | |
module ActiveRecord::NudgeableAssociation | |
def self.included(base) | |
base.extend ClassMethods | |
(class << base; self; end).instance_eval do | |
alias_method_chain :belongs_to, :nudge | |
end | |
end | |
module ClassMethods | |
def belongs_to_with_nudge(name, options = {}) | |
if nudge_attribute = options.delete(:nudge) | |
add_nudge_callbacks(name, nudge_attribute) | |
end | |
belongs_to_without_nudge(name, options) | |
end | |
private | |
def add_nudge_callbacks(association_name, nudge_attribute) | |
method_name = "belongs_to_nudge_after_save_or_destroy_for_#{association_name}".to_sym | |
define_method(method_name) do | |
association = send(association_name) | |
return if association.nil? | |
if nudge_attribute == true | |
association.nudge | |
else | |
association.nudge(nudge_attribute) | |
end | |
end | |
after_save(method_name) | |
after_destroy(method_name) | |
end | |
end | |
def nudge(attribute = nil) | |
current_time = current_time_from_proper_timezone | |
if attribute | |
write_attribute(attribute, current_time) | |
else | |
write_attribute('updated_at', current_time) if respond_to?(:updated_at) | |
write_attribute('updated_on', current_time) if respond_to?(:updated_on) | |
end | |
save! | |
end | |
end | |
ActiveRecord::Base.instance_eval { include ActiveRecord::NudgeableAssociation } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment