I am new to ruby on rails and am writing a simple database application...
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 do...
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 << Language.new( :name => lang )
end
it created new enteries in languages table and then added into relation...
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
plz...
awaiting your response...
People succeed in answering Vishwajith's questions 50% of the time (1 success in 2 attempts).
Answers by: Rich Collins
@person.languages = array_of_language_objects
This will remove the old entries from the join table and add new ones. The former language objects will not be deleted.
If the language objects are new records, they will be saved to the languages table first.
wow... thats easier than i thought..
thanx a lot..
Sorry I missed you - I was not at my computer - I will be online for a few more minutes if you would like to chat.
actually i implemented your answer and my program is working fine... thanx again..
i just had one more query...
if i create an array of langs and assign it to person.languages,
should the array be generated from Language.new or Language.find_by_name ???
say vishwa has 2 langs english and french [ both in the join table ]
if i assign vishwa.languages = array with ( english , spanish ) both english and spanish created by Language.new method...
will it work... or should i create the array using Language.find_by_name method..
ok all right...
i was using guruza for the first time..
so didnt really know how to use chat..
so had that problem... :)
thanx a lot...