如何使用子窗体保存父对象属性

时间:2013-07-26 02:18:21

标签: ruby-on-rails nested-attributes

这些是我的模特:

class Parent < ActiveRecord::Base
    has_one :child, :dependent => :destroy
end

class Child < ActiveRecord::Base
    belongs_to :parent
    accepts_nested_attributes_for :parent
end

我的目标是在创建子项时更新1父属性(电子邮件)(这意味着最终用户位于控制器操作为“新”的子窗体上)

Hay que tener en cuenta que simpre cuando quiera crear el child,existe ya antes de antes un parent en la db。

我的孩子控制员:

def new
    @child = Child.new
    @child.parent = current_parent
end 


def create
    @child = Child.new(params[:child])
    @child.parent = current_parent


    respond_to do |format|
        if @child.save
        #.....
        else
            format.html { render :action => "new" }
        end
    end
end

儿童表格:

<% form_for @child, :html => {:multipart => true} do |f| %>
......
<% f.fields_for :parent do |p| %>
    <%= p.label :email, t(:label_child_email), :req => true %>
    <%= p.text_field :email, :class => "field" %>
<% end %>

<%end%>

当用户点击“保存”按钮时,他们会:

无法找到ID为= 4147且ID为

的Child的父级

参数:

{"commit"=>"Save",
     "child"=>{
         ...........
         "parent_attributes"=>{"email"=>"blabla@dada.com", "id"=>"4147"
     },
         ..........
}

你知道什么是错的吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您正在构建孩子的方式导致了问题。请尝试以下

def new
    @child = current_parent.build_child
end 

def create
    @child = current_parent.build_child(params[:child])
    // more code
end

查看build_association和create_association here