I have an array of contact ids and an array of group ids. I’m trying to loop through all the contacts and add them to the group if they aren’t already in the group. The relationship is as follows:
class Contact < ActiveRecord::Base
has_many :contact_groups
has_many :groups, :through => :contact_groups
end
class ContactGroup < ActiveRecord::Base
belongs_to :contact
belongs_to :group
end
class Group < ActiveRecord::Base
has_many :contact_groups
has_many :contacts, :through => :contact_groups
end
Here’s what I’m currently doing which works. However, the code is clunky. It’s the has_many :through relationship that’s throwing me for a loop… literally:
for contact in params[:contact]
for group in params[:group]
ContactGroup.find_or_create_by_contact_id_and_group_id(contact, group)
end
end