Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.