How to create a child from a parent

Hi i am trying to figure out what is the best way to do this very basic
thing:
lets say i have two tables: one with parents and one with children.
there is a one to many relation between them.

I scaffolded the parents tabel and i can open each parent. Now i want to
add a link to the ‘show’ view which will create a new child record.

In the model i defined the has_many and belongs_to relations between the
children an parents but i dont know what i have to do in the controller
part in order to fill the foreign key field of the child table.

in some example i saw in the controler someting like:

@parent = Parent.find(params[:id])
@child.parent = @parent
@child.save

but that doesn’t seem to work in my test application, the child saves
but the foreign key is null

on the other hand, if i do
@child.parent_id=parent.id
that works but i am not sure that is the way to go, because for that i
don’t have to define the relations in the model, this will work anyway

hope someone can give me some pointers for this very basic question

regards,

Remco

remco hh wrote on 13.07.2006 10:20:

Hi i am trying to figure out what is the best way to do this very basic
thing:
lets say i have two tables: one with parents and one with children.
there is a one to many relation between them.
[…]
@child.parent_id=parent.id
that works but i am not sure that is the way to go, because for that i
don’t have to define the relations in the model, this will work anyway

I think you have a wrong association.
If childs table has a column parent_id then the child belongs_to parent.
If parents table has a column child_id then the child has_one parent.
But I think you want to do the first and then your found example works.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs