inye
inye

Reputation: 1796

Rails direct method to update join table association?

I am looking for a direct method to update a jointable asociation

An example is: I have Project (id: 45) and some people are working on it (Person id 10 and Person id 12)

The jointable is persons_projects whith

...
person_id: 10 project_id: 45
person_id: 12 project_id: 45
...

And in some point the people leave, arrive and or not. Example Person id 12 leave, Person id 10 stay and Person id 33 arrive.

The "long" way was to insert to persons_projects check actual people [10 , 33] and check on old people [10,12] if not exist create and to delete in persons_projects check the old people in new people, if not exist delete them.

This take 2 loop, but I think there are a ruby short method like

Project.persons.delete_or_create_bla([10 , 33])

Upvotes: 1

Views: 329

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

Project.find(45).person_ids = [10 , 33]

This will add 2 entries in join_table

[45, 10] and [45, 33] and remove other entries with project_id = 45 i.e [45, 12]

You can also push the entry instead of updating with

Project.find(45).person_ids << 33

this will keep [45, 10] and [45, 12] and also add [45, 33]

Upvotes: 1

Related Questions