Appending a record in many to many relationship

Hello,
I have the following mailinglist and people model

class Mailinglist < ActiveRecord::Base
has_and_belongs_to_many :people
end

class Person < ActiveRecord::Base
has_and_belongs_to_many :mailinglists
end

Now, i have created a form to search people. In the result of the search
there is
a checkbox beside each result. i tick the checkbox and write the
mailinglist name in the textbox provided on the results page.

THE PROBLEM IS IF THE LIST IS ALREADY CREATED AND IF I WANT TO ADD
ANOTHER PERSON TO THE LIST HOW CAN I DO THAT.

IF I USE UPDATE_ATTRIBUTES THE OLD PEOPLE ARE MOVED OUT OF THE LIST AND
ONLY THE NEW ONES are added. i want to add the new people to the list
without removing the old ones.
my three tables are
people
mailinglists
mailinglists_people
i HAVE A COMBO BOX SELECTION on the result page TO SELECT THE LIST IN
WHICH I NEED TO ADD PEOPLE.

Thank you.

this should do it:

@mailing_list = MailingList.find(…)
@person = Person.find(…)

@mailing_list.people << @person

only that:

class Mailinglist < ActiveRecord::Base
has_and_belongs_to_many :people
end

should be:

class Mailinglist < ActiveRecord::Base
has_and_belongs_to_many :persons
end

then my last line:
@mailing_list.people << @person
should be
@mailing_list.persons << @person

or you have used :foreign_key ?

@Thorsten

end
The association is defined correctly. Check your console:

“person”.pluralize

=> “people”

@Ank
You might also consider using a named association rather than
has_and_belongs_to_many because it gives you much more control over
the association.

For example:

class MailingList < ARec::Base
has_many :subscriptions
has_many :people, :through => :subscriptions
end

class Subscription < ARec::Base
belongs_to :mailing_list
belongs_to :person
end

class People
has_many :subscriptions
has_many :mailing_lists, :through => :subscriptions

for convenience

def subscribe(mailing_list)
subscriptions.create(:mailing_list=>mailing_list)
end
end

Then Thorsten’s code would be:
@mailing_list = MailingList.find(…)
@person = Person.find(…)
@person.subscribe(@mailing_list) if @mailing_list && @person

Thorsten M. wrote:

this should do it:

@mailing_list = MailingList.find(…)
@person = Person.find(…)

@mailing_list.people << @person

only that:

class Mailinglist < ActiveRecord::Base
has_and_belongs_to_many :people
end

Thanks a ton…

Hi Andy,
thank you for correcting me there, english is not my
native language, so i went for the simple form

and of course you’re right, i can’t even think
of any code where i ever used the basic habtm relationship myself :slight_smile: