안녕하세요, 한 양식에서 동시에 두 개의 테이블에 저장하려고합니다. 내가 만든 Contact
와 has_many
의 관계 .Order
belongs_to
Contact
models / contact.rb
class Contact < ActiveRecord::Base
has_many :orders
accepts_nested_attributes_for :orders, reject_if: :all_blank
end
models / order.rb
class Order < ActiveRecord::Base
belongs_to :contact
end
다음과 같이 보이는 OrdersController도 만들었습니다.
controllers / OrdersController.rb
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
이름이 주문 테이블에 존재하지 않아 불만이 있다고 가정하지만 연락처 테이블에는 존재합니다. 이것을 다르게 만들어야합니까?
나는 또한 @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>
1) 첫 번째 요점은 생성 방법이 @ordar.save
대신 Typo로@order.save
가정하는 것입니다.
2) 두 번째 요점은 @order = @contact.orders.build(order_params)
이 선이 필요하지 않으며 order_params
단순히@order = @contact.orders.build
따라서 이러한 변경으로 인해 생성 작업은
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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다