您好我想從一個表單同時保存到兩個表。 我已創建Contact
與has_many
的關係Order
其中belongs_to
Contact
。嘗試保存到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
的OrdersControllerclass 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>
你採取了@@ ordar.save而不是'@ order.save',那是一個錯字? – Sravan
這一行'@order = @ contact.orders.build(order_params)'應該再次'@order = @ contact.orders.build'當構建時不需要'order_params' – Sravan