Problem with joining

Hello,

I am quite new to Rails and i was wondering if i could get some help
to populate a join table?
I got (for example) a table called films, a table called acteurs and
a join table called acteurs_films. I have specified the HABTM
relationship and I manage to do it through the console by doing:

acteur=Acteur.new
acteur.name=“blabla”
acteur.films << film
acteur.save

and it works! That’s great but when i go back to coding i don’t
really understand how to do it then!!?
Do i need to put the code in the model and the controller or just the
controller?

I know this might sound confusing but, please, if somebody out there
understand, help would be much appreciated!=)

Thanks.

Olivier Meyer wrote:

Hello,

I am quite new to Rails and i was wondering if i could get some help
to populate a join table?
I got (for example) a table called films, a table called acteurs and
a join table called acteurs_films. I have specified the HABTM
relationship and I manage to do it through the console by doing:

acteur=Acteur.new
acteur.name=“blabla”
acteur.films << film
acteur.save

and it works! That’s great but when i go back to coding i don’t
really understand how to do it then!!?
Do i need to put the code in the model and the controller or just the
controller?

I know this might sound confusing but, please, if somebody out there
understand, help would be much appreciated!=)

Thanks.

You would do that in your controller, or if you want to encapsulate the
functionality to be reusable, you can do it in the model. And you
already figured out the code for it!

Consider the following controller action

def add_film_to_actor
@actor = Actor.find(params[:actor_id])
@actor.films << Film.find(params[:film_id])
@actor.save
end