ruby Rails 7中使用多态关联的不允许参数

4ioopgfo  于 11个月前  发布在  Ruby
关注(0)|答案(1)|浏览(119)


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

型号:人

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控制台运行时,根据下面的代码,这是可以的。

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中,但我没有找到解决它的方法。

z0qdvdin

z0qdvdin1#

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)。

相关问题