There's got to be a better way!

Hi,

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

Is there a better way?

Thanks!
-Dave

Hi Cayce,

I tried your suggestion but I keep receiving an error that reads:

undefined method `contacts’ for #Array:0x246be0c

This is how I implemented your suggestion:

@group = Group.find(params[:group])
Contact.find(params[:contact]).each {|c| @group.contacts << c unless @group.contacts.include?©}

params[:group] and params[:contact] hold an array of IDs that originate from a series of check boxes.

I’m pretty sure the relationships are set up right, so I’m kind of lost as to why this undefined method error is occurring.

Thanks,
Dave

Hi --

Cayce,

That worked like a charm! Learning Rails before really learning Ruby makes some things harder than what they really should be.

David,

I think it’s a good idea to eagerly load the contacts like you suggested.

Thanks to all that helped!
-Dave

Hi --

I actually do own that book (and I thank you for writing it!). There’s so much info in there. Takes awhile to get through it :slight_smile: