Skip to content

Instantly share code, notes, and snippets.

@dmitry
Created February 5, 2011 01:54
Show Gist options
  • Save dmitry/812120 to your computer and use it in GitHub Desktop.
Save dmitry/812120 to your computer and use it in GitHub Desktop.
has_many_ids
class ActiveRecord::Base
def self.has_many_ids(association, ids, options={})
options = {:typecast => :to_sym}.merge(options)
method_name = :"#{association.to_s.singularize}_#{ids.to_s.pluralize}"
define_method method_name do
self.send(association).map(&ids)
end
define_method :"#{method_name}=" do |new|
collection = self.send(association)
old = self.send(method_name)
new = new.select(&:present?).map(&options[:typecast])
(new - old).each do |v|
collection.create!(ids => v)
end
delete_ids = (old - new).map { |value| collection.detect { |v| v.send(ids) == value } }
collection.destroy(delete_ids)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment