public
Last active

has_many_ids

  • Download Gist
has_many_ids.rb
Ruby
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.