Skip to content

Instantly share code, notes, and snippets.

@suras
Created March 29, 2014 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suras/9860400 to your computer and use it in GitHub Desktop.
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
# 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