Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

has_many_ids

View has_many_ids.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
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.