2013-07-26 40 views
3

這些都是我的模型保存父對象的屬性:如何使用子窗體

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

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

我的目標是更新1 parent屬性(電子郵件)時,我創建子(這意味着最終用戶在控制器操作是「新」的子表單)

這樣的表單可以用於控制器操作是「新的」)

我的孩子控制器:

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 =

而第米:

{"commit"=>"Save", 
    "child"=>{ 
     ........... 
     "parent_attributes"=>{"email"=>"[email protected]", "id"=>"4147" 
    }, 
     .......... 
} 

你知道怎麼回事嗎?

謝謝!

回答

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

+0

在新的動作,我越來越_undefined方法'建設」爲無:NilClass_ – ratamaster

+0

對不起我bad..I已經更新了我的代碼。 – Josnidhin

+0

謝謝你的回覆!現在在新動作中沒有錯誤,但是當我嘗試保存(創建動作)時,我得到了這個:** _無法找到ID = 4148的ID爲ID爲**的孩子** 看起來我首先必須創建孩子,然後更新父... – ratamaster

相關問題