2017-01-30 21 views
0

您好,我想通過使用客戶ID在其他表中插入客戶城市來在一個表中插入客戶名稱。 我的代碼只插入客戶。城市不插入將表單數據插入到兩個表中,其中一個在rails中提交

我的控制檯

在2017年1月30日14時四十分15秒0530 處理由PagesController#入門POST「/頁」爲127.0.0.1創建爲HTML參數: { 「UTF8」=> 「✓」, 「authenticity_token」=> 「NfyA8PpA4wZIAOPX7fYstwvt2suXoTYgl9ep1M6yTSh6ZPX8lt + oOfPX6sFXGOuxTidVND6qaksz6iZ2enGj9g ==」, 「客戶」=> { 「名稱」=> 「fgfg」, 「custcity」=> { 「城市名」 =>「2fg」}}, 「commit」=>「submit」}不允許的參數:custcity(0.1ms)begin 事務SQL(2.3ms)INSERT INTO「customers」(「name」, 「created_at」,「updated_at」)VALUES(?,?,?)[[「name」,「fgfg」], [「created_at」,2017-01-30 09:10:15 UTC],[「updated_at 「,2017-01-30 09:10:15 UTC]](231.7ms)commit transaction(0.2ms)begin transaction(0.1ms)rollback transaction重定向到 http://localhost:3000/pages已完成302已在247ms中找到 (ActiveRecord:234.3ms )

new.html.erb

<%= form_for @customer, url: {action: "create"} do |f| %> 
<%= label_tag("Customer") %> 
<br> 
<%= f.text_field(:name) %> 
<br> 
<%= f.fields_for @custcity do |c| %> 
     <%= label_tag("City 1") %> 
     <br> 
     <%= c.text_field(:cityname) %> 
     <br> 
     <%= label_tag("City 2") %> 
     <br> 
     <%= c.text_field(:cityname) %> 
     <br> 
<% end %> 
<br> 
<%= f.submit("submit") %> 
<% end %> 

pages_controller.rb

def create 
    @customer = Customer.new(cust_params) 
    if @customer.save 
     session[:customer_id] = @customer.id 

     #@custcity = Custcity.create(cityname: params[:customer][:cityname], cust_id: session[:customer_id]) 
     @custcity = Custcity.create({cityname: params[:customer][:cityname], cust_id: @customer.id}) 
     #@custcity.save 
     redirect_to pages_path 
    else 
     redirect_to new_page_path 
    end 
    end 

    private 
    def cust_params 
    params.require(:customer).permit(:name, :custcity => []) 
    end 
end 
+0

你應該使用強嵌套的參數和強參數定義客戶城市PARAMS。 –

回答

1

錯誤的路徑爲:cityname鍵。你已經失去了:custcity

@custcity = Custcity.create({cityname: params[:customer][:custcity][:cityname], cust_id: @customer.id}) 

許可證cityname太:

params.require(:customer).permit(:name, :custcity => [:cityname]) 
+0

這會返回錯誤'unknown attribute custcity' –

+0

按照想法,Customer和Custcity模型應該與has_many關聯關聯,並且您不需要手動調用'Custcity.create'。 –

相關問題