Rails 5:嵌套参数未嵌套 has_many :through

Rails 5: Nested params not nested with has_many :through

我正在尝试在 Rails 5.2 中为与另一个模型具有 has_many :through 关系的模型创建一个表单。表单需要包含其他模型的嵌套属性。但是,参数没有正确嵌套。我创建了以下最小示例。

这是我的模型:

class Order < ApplicationRecord
  has_many :component_orders, dependent: :restrict_with_exception
  has_many :components, through: :component_orders

  accepts_nested_attributes_for :components
end

class Component < ApplicationRecord
  has_many :component_orders, dependent: :restrict_with_exception
  has_many :orders, through: :component_orders
end

class ComponentOrder < ApplicationRecord
  belongs_to :component
  belongs_to :order
end

ComponentOrder 模型各有一个属性::name

这是我的表单代码:

<%= form_with model: @order do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= fields_for :components do |builder| %>
    <%= builder.label :name %>
    <%= builder.text_field :name %>
  <% end %>

  <%= f.submit %>
<% end %>

当我填写表格时,我得到以下参数:

{"utf8"=>"✓", "authenticity_token"=>"ztA1D9MBp1IRPsiZnnSAIl2sEYjFeincKxivoq0/pUO+ptlcfi6VG+ibBnSREqGq3VzckyRfkQtkCTDqvnTDjg==", "order"=>{"name"=>"Hello"}, "components"=>{"name"=>"World"}, "commit"=>"Create Order", "controller"=>"orders", "action"=>"create"}

具体来说,请注意而不是像这样的参数:

{
  "order" => {
    "name" => "Hello", 
    "components_attributes" => {
      "0" => {"name" => "World"}
    }
  }
}

"order"和"components"在同一级别有不同的键。我怎样才能使这些属性正确嵌套?谢谢!

编辑:这是我的控制器代码:

class OrdersController < ApplicationController
  def new
    @order = Order.new
  end

  def create
    @order = Order.new(order_params)
    if @order.save
      render json: @order, status: :created
    else
      render :head, status: :unprocessable_entity
    end
  end

  private

  def order_params
    params.require(:order).permit(:name, components_attributes: [:name])
  end
end

您应该在 Order 模型中包含 accepts_nested_attributes_for :components

class Order < ApplicationRecord
  has_many :component_orders, dependent: :restrict_with_exception
  has_many :components, through: :component_orders
  accepts_nested_attributes_for :components
end

并改变

<%= fields_for :components do |builder| %>

<%= f.fields_for :components do |builder| %>

得到想要的paramsaccepts_nested_attributes_for :components 创建一个方法即 components_attributes

更多信息here