的数据
根据上面的图片,我做了一个简单的例子。
型号:人
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中,但我没有找到解决它的方法。
1条答案
按热度按时间z0qdvdin1#
Rails期望
person
属性嵌套在person_attributes
下,但表单却在person
下发送它们。要解决这个问题,请确保
fields_for
正确设置了person_attributes
下嵌套的字段,格式如下:字符串
这将为嵌套属性生成正确的参数名(
person_attributes
)。