<- TutorialFramingOut | Beginning: [[Tutorial]] ->
Editing the phone numbers for each person is a little trickier because of the many to one relation.  Let's   modify @edit.rhtml@ to allow us to edit phone numbers. 

Add this to the edit.rhtml file:

<pre>
<p>Phones</p>

<p><% @person.phones.each { |phone| %>
<%= tag("input", "type" => "text",  "id" => "phones[#{phone.id}][phone]", "name" => "phones[#{phone.id}][phone]", "value" => phone.phone) %>
<%= phone.errors.on "phone" %><br/>
<% } %></p>

<p>Add new phone: (More phones can be added later)<br />
<input type="text" id="phones[new][phone]" name="phones[new][phone]" value="">
</p>
</pre>

Yeah, that got a little ugly.  At the moment, the text_field helper object doesn't allow more complex name attributes, so we had to roll our own using the tag helper. Since we have many phone items, we put each one in an hash indexed by the phone id.  This means data will be passed back to the controller as:

<pre>
@params["phones"][1]["phone"] # >> 555-1234
@params["phones"][2]["phone"] # >> 555-6533
</pre>

Here's some updated controller code to parse that:

<pre>
  def update
    @person = Person.find(@params["person"]["id"])
    @person.attributes = @params["person"]
    
    saved = @person.save
    new_empty = false
    
    @params["phones"].each { |key, value|
      if key == "new" 
        phone = @person.build_to_phones(value)
        new_empty = true if value["phone"].empty?          
      else
        phone = Phone.find(key)
        phone.attributes = value
      end
      
      unless phone.phone.empty?
        saved = false unless phone.save
      end
    }
    
    if saved and new_empty
      redirect_to :action => "show", :id => @person.id
    else
      @target = "update" 
      render "friends/edit" 
    end
  end
</pre>

Notice how we loop through each of the key/value pairs, updating exisiting phones and possibly adding a new one.  This form allows us to add one phone at a time.  We get redirected back to the edit page as long as we are adding a new phone number.

Note: ActiveRecord automagically creates the _build_to_phones_ method for you.

Congratulations, you've finished the tutorial!  You can go return to [[Tutorial]] to revise what you've covered so far.

<- TutorialFramingOut | Beginning: [[Tutorial]] ->

category:Tutorial
