Rails 5:嵌套的params没有嵌入has_many:through

问题描述 投票:1回答:1

我正在尝试在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"}
    }
  }
}

“订单”和“组件”在同一级别有单独的键。如何使这些属性正确嵌套?谢谢!

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

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
ruby-on-rails nested-forms
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.