Created
March 29, 2014 18:42
-
-
Save suras/9860400 to your computer and use it in GitHub Desktop.
rails has_and_belongs_to_many enabling touch updated_at when hasbtm association is created
This file contains 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
# include this module in models where adding record of has_and_belongs_to_many asscociation | |
# changes the updated_at column of included model. | |
module HabtmTouchId | |
extend ActiveSupport::Concern | |
included do | |
after_initialize :create_touch_true_has_and_belongs_to_many | |
end | |
def create_touch_true_has_and_belongs_to_many | |
association = self.class.name.constantize.reflect_on_all_associations(:has_and_belongs_to_many) | |
association.each do |assoc| | |
next if assoc.plural_name.blank? | |
name = assoc.plural_name.chop!+"_ids=" | |
self.class.send(:define_method, name, lambda { |ids| | |
self.updated_at = Time.now | |
super(ids) | |
}) | |
end | |
end | |
end | |
the module will update the updated_at column when a hasbtm association is created with (attribute)_ids method eg tag_ids = [1, 2,3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment