尝试保存到 Rails 中的父表和子表,但在嵌套属性上出现参数错误

Trying to save to Parent and child tables in Rails, but get argument error on nested Attributes

您好,我正在尝试从一个表格同时保存到两个 table。 我创建了 ContactOrderhas_many 关系 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 admin@careerfalir.co.za"
            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

名称在订单 table 中不存在,这就是我认为它在抱怨的原因,但它确实存在于联系人 table 中。我应该以不同的方式创建它吗?

我也试过 @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 而不是 @order.save 我假设为 Typo

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 admin@careerfalir.co.za"
        redirect_to new_order_path
    end
end