2017-02-16 29 views
0

您好我想從一個表單同時保存到兩個表。 我已創建Contacthas_many的關係Order其中belongs_toContact嘗試保存到Rails中的父表和子表,但在嵌套的屬性上獲取參數錯誤

型號/ contact.rb

class Contact < ActiveRecord::Base 
    has_many :orders 
    accepts_nested_attributes_for :orders, reject_if: :all_blank 
end 

型號/ order.rb

class Order < ActiveRecord::Base 
    belongs_to :contact 
end 

我也創建看起來如下

控制器/ OrdersController.rb

的OrdersController
class OrdersController < ApplicationController 
    def new  
     @contact = Contact.new 
     @contact.orders.build 
    end 

    def create 
     @contact = Contact.new(order_params) 
     if @contact.save 
      @order = @contact.orders.build(order_params) 
      @order.save 
      flash[:success] = "Your has been sent we'll get back to you shortly" 
      redirect_to new_order_path 
     else 
      flash[:danger] = "We were unable to process your request please try again or email [email protected]" 
      redirect_to new_order_path 
     end 
    end 

    . . . 
    private 
     def order_params 
      params.require(:contact).permit(:id,:name,:surname, :email, :comments, :dob, :phone_number, :contact_method, orders_attributes: [:email, :contact_id,:package,:jobs_strategy,:fast_turn_around,:order_comments, :contact_email]) 
     end 
end 

當我嘗試和創造,我得到一個錯誤未知屬性的順序:命名

@contact = Contact.new(order_params) 
    if @contact.save 
     *** @order = @contact.orders.build(order_params) *** This is the line with the error 
     @ordar.save 
     flash[:success] = "Your has been sent we'll get back to you shortly" 
     redirect_to new_order_path 

名稱不Orders表上存在,爲什麼我認爲它是抱怨,但它確實在聯繫人表中。我應該創造這種不同?

我也試過@order = @contact.orders.create(order_params)與同樣的錯誤。

這裏是視圖

<%= form_for @contact, url: orders_path do |f| %> 

     <div> 
      <%= f.label :name %> 
      <%= f.text_field :name, class:"form-control" %> 
     </div> 
     <div> 
..... 
    <%= f.fields_for :order do |order| %> 
     <div> 
      <%= order.label :package %> 
      <%= order.text_field :package, class: "form-control" %> 
     </div> 
+0

你採取了@@ ordar.save而不是'@ order.save',那是一個錯字? – Sravan

+0

這一行'@order = @ contact.orders.build(order_params)'應該再次'@order = @ contact.orders.build'當構建時不需要'order_params' – Sravan

回答

0

1)第一點是所述創建方法的@ordar.save代替@order.save其中我假定爲錯字

2)的樣品的第二點是@order = @contact.orders.build(order_params)這條線不需要order_params,應該是簡單的@order = @contact.orders.build

所以這些改變你的創建acti on應該是,

def create 
    @contact = Contact.new(order_params) 
    if @contact.save 

     flash[:success] = "Your has been sent we'll get back to you shortly" 
     redirect_to new_order_path 
    else 
     flash[:danger] = "We were unable to process your request please try again or email [email protected]" 
     redirect_to new_order_path 
    end 
end 
+0

我的歉意確實是一個錯字。 這擺脫了錯誤,並保存到它的表,但沒有采取任何我的參數爲訂單表 – Jacques

+0

好吧,沒有必要再次建立'訂單',檢查更新的答案。 – Sravan

+0

@Jacques,現在檢查我的答案? – Sravan