rmcsharry
rmcsharry

Reputation: 5552

Rails: how to retrieve the params for child objects in nested form

I have a wizard situation where I create a Parent object, and then build a form with 2 nested children.

The parameters that get submitted look like this:

Parameters: {"room"=>
{"parents_attributes"=>
{"0"=>{"name"=>"r2", "phone"=>"07443107986"},
 "1"=>{"name"=>"", "phone"=>""}}},
 "commit"=>"Go!", "id"=>"step03"}

(the commit and id are from the wicked wizard step)

If the user refreshes the page, the id's for these children change and the parameters look like this:

Parameters: {"room"=>
{"parents_attributes"=>
{"1"=>{"name"=>"r2", "phone"=>"07443107986"},
 "2"=>{"name"=>"", "phone"=>""}}},
 "commit"=>"Go!", "id"=>"step03"}

Since the id's are generated by the fields_for.

My controller code retrieves the data like this (the room is saved in the session on a previous step):

    @room = Room.find(session[:room_id])
    @room.parents.build(room_params[:parents_attributes]['0'])
    @room.parents.build(room_params[:parents_attributes]['1'])

This obviously only works if the user does not refresh the page. Also, if validations fire the id's of the children change too.

What is a better way to retrieve these parent_attributes from the params hash?

EDIT

In the wizard step, the child objects are built like this:

when :step03
  @room = Room.find(session[:room_id])
  2.times{ @room.parents.build }

Upvotes: 2

Views: 997

Answers (1)

dp7
dp7

Reputation: 6749

You can try following to extract hash keys dynamically:

room_params[:parents_attributes].each {|k,_| @room.parents.build(room_params[:parents_attributes][k])}

Upvotes: 1

Related Questions