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
Looks like Group.find(params[:group]) is returning an Array rather than
a single instance of Group. To use Cayce’s algorithm (nicely done, by
the way), @group will need to represent a single instance of Group
Cheers.
Yep, that’s definitely the problem. Initially, I’d have said try this…
Only - this is going through all contacts in the database and adding
those that don’t exist in the group. I’m gathering from your second post
that what you’re after is to add all contacts in params[:contact] to all
groups in params[:group]. In that case, you just need to change the
Contact.find() parms - this should work for you…
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
Looks like Group.find(params[:group]) is returning an Array rather than
a single instance of Group. To use Cayce’s algorithm (nicely done, by
the way), @group will need to represent a single instance of Group
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
Well, this is not at all self serving.
Let me just say that being on my second time through David’s book
(amazing the things that you pick up on once you have a bit of
undertanding under your belt.) and having attended a week long bootcamp
that he taught, the book really should be required reading.