Help on updating has_and_belongs_to_many relationships

I am new to ruby on rails and am writing a simple database

I have people table and languages table…
they have m:n relationship using languages_people table [
has_and_belongs_to_many ]

now i was able to access all langs for a person using just
person1.languages [ array of language]

i have displayed it to front end … which will be edited and sent back
to the controller…

here i need to update the languages of that person…

i dont know how to do it…

i tried to delete all previous languages and then addnew all of them

but was not able to…

as i am very new to this framework, i dont have a clue as to what to
After reading the features offered by ruby on rails I am very much sure
that there is a simple and easy way to do this …

can anyone help me… giving me the syntax to delete all languages
corresponding to a person , and adding languages into it will be
great… [ if there is a better method plz let me know…]

when i tried to add them using [ here i have copied all langs from
frontend to temp_langs]

for lang in temp_langs
@person.languages << :name => lang )

it created new enteries in languages table and then added into
which is not what i want…
i dont want to add a new entry into languages table …
i want to add an entry only in the languages_people table


awaiting your response…

It sounds like you need to use has_many :through. It makes your join
table a real fully functional model. This makes relationships much
easier to manage because you can edit the join records directly, and
even have other fields on the join like how long this person has spoken
this language, or how well they speak it.

It does everything has_and_belongs_to_many does and much much more.
Here is some sample code to show you how you can use it.

class Person
has_many :languages, :through => :fluencies
has_many :fluencies

class Language
has_many :people, :through => :fluencies
has_many :fluencies

class Fluency
belongs_to :people
belongs_to :language

#usage eamples
p = Person.create(:name => ‘Bob’)

french = Language.find_by_name(‘French’)
german = Language.find_by_name(‘German’)

p.fluencies.create(:language => french)
p.languages << french #same as above but edge rails only (I think)

#=> [<#Language @name=‘French’>]

Fluency.create(:language => german, :person => p)

#=> [<#Language @name=‘French’>, <#Language @name=‘German’>]

hi Alex,

I didnt know that one can use has_many for m:n relationships using
This looks better for my program…
Thanx for taking time to write the class code… or i would have found
it diff to understand…