嵌套属性未保存

时间:2010-10-08 19:08:55

标签: ruby-on-rails forms

我有一个用于创建/编辑活动的表单。有一个客户端下拉列表,它会根据所选客户端呈现一些自定义问题和答案。

我在Windows上使用Ruby 1.8.6和Mongrel运行Rails 2.3.9。 以下是相关代码:

活动表格

- 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

事件控制器

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

参数哈希

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

基本上,表单传递验证和除嵌套属性之外的所有内容。没有任何内容插入数据库表。

查看参数hash我的client_attributes没有id ...嗯......

1 个答案:

答案 0 :(得分:2)

在client_fields partial中,我必须添加以下代码来设置client_attributes_id:

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

自我注意:当你不使用Rails的魔术形式助手时,你也必须构建表格的其余部分。

相关问题