Rails 5:不与has_many嵌套的嵌套参数:through

时间:2018-09-15 18:30:00

标签: ruby-on-rails nested-forms

我正在尝试在Rails 5.2中为与另一个模型具有constexpr int GLOBAL_CONST_VAR{ 0xff }; 关系的模型创建表单。该表格需要包括其他模型的嵌套属性。但是,参数不能正确嵌套。我创建了以下最小示例。

这是我的模特:

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 Component模型分别具有一个属性:Order

这是我的表单代码:

: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"}
    }
  }
}

1 个答案:

答案 0 :(得分: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