Rails 7 中使用多态关联的未经允许的参数

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

enter image description here

根据上图,我做了一个简单的例子。

型号:人

class Person < ApplicationRecord
  belongs_to :personable, polymorphic: true
end

型号:客户

class Customer < ApplicationRecord
  has_one :person, as: :personable
  accepts_nested_attributes_for :person
end

控制器:customers_controller

def new
  @customer = Customer.new
  @customer.build_person
end

def create
  @customer = Customer.new(customer_params)
  @customer.save
  redirect_to customers_path
end

private

def customer_params
  params.require(:customer).permit(:id, person_attributes: [:id, :name, :personable_type, :personable_id])
end

查看

<%= form_with(model: customer) do |form| %>
  <%= form.fields_for customer.person do |form_fields| %>
    <%= form_fields.label :name %>
    <%= form_fields.text_field :name %>
  <% end %>
  <div>
    <%= form.submit %>
  </div>
<% end %>

当我使用 Rails Console 运行时,没有问题,根据下面的代码。

c = Customer.create()
Person.create(name: "Saulo", personable: c)

但是当我使用视图和控制器运行时,我收到以下错误。

Unpermitted parameter: :person. Context: { controller: CustomersController, action: create, request: #<ActionDispatch::Request:0x00007fdad45e3650>, params: {"authenticity_token"=>"[FILTERED]", "customer"=>{"person"=>{"name"=>"Alisson"}}, "commit"=>"Create Customer", "controller"=>"customers", "action"=>"create"} }

我相信错误出现在 customer_params 方法中,但我没有找到解决方法。

ruby-on-rails ruby nested-attributes ruby-on-rails-7
1个回答
0
投票

Rails 期望

person
属性嵌套在
person_attributes
下,但表单将它们发送到
person
下。

要解决此问题,请确保

fields_for
正确设置要嵌套在
person_attributes
下的字段,格式为:

<%= form_with(model: [customer, customer.build_person]) do |form| %>
  <%= form.fields_for :person_attributes, customer.person do |person_form| %>
    <%= person_form.label :name %>
    <%= person_form.text_field :name %>
  <% end %>
  <%= form.submit %>
<% end %>

这应该为嵌套属性生成正确的参数名称 (

person_attributes
)。

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