views:

32

answers:

1

I have a form for creating/editing an event. There is a Client drop down which renders some custom questions and answers dependent on the selected Client.

I'm running Rails 2.3.9 with Ruby 1.8.6 and Mongrel on Windows. Here is the relevant code:

Event form

- form_for @event do |f|
    ....
    = f.collection_select(:client_id, Client.all, :id, :name)

    #custom_client_fields
      = render 'client_fields' if @client

    = observe_field :event_client_id, :url => {:action => 'client_fields'}, 
                    :with => "'client_id=' + encodeURIComponent(value)"
    ....

_client_fields.html.haml

- fields_for "event[client_attributes]", @client do |client|
  - client.fields_for :questions do |question|
    %label.question= question.object.content
    - question.fields_for :answers, Answer.new do |answer|
      = answer.text_field:content, :maxlength => 150, :size => 40

Event Controller

def client_fields
  if params[:client_id].blank?
    render_no_client_fields #self explanatory
  else
    respond_to do |format|
      format.js {
        render :update do |page|
          page[:custom_client_fields].replace_html :partial => 'client_fields', :layout => false
        end
      }
    end
  end
end

Parameter hash

Parameters: {
  "event"=>{
    "id"=>"2",
    "client_attributes"=>{
      "questions_attributes"=>{
        "0"=>{
          "id"=>"4",
          "answers_attributes"=>{
            "0"=>{
              "content"=>"fjhkghjkk"
            }
          } 
        }
      }
    }
  }
}

Basically the form passes the validations and everything except the nested attributes. Nothing is inserted into the database table.

Looking at the parameter hash my client_attributes doesn't have an id... hmmm...

A: 

In the client_fields partial I had to add the following code to set the client_attributes_id:

<input id="event_client_attributes_id" name="event[client_attributes][id]" type="hidden" value="#{@client.id}">

Note to self: When you don't use Rails' magic form helpers you have to build the rest of the form as well.

Nate Bird