提问人:Saulinho 提问时间:11/4/2023 最后编辑:James HibbardSaulinho 更新时间:11/4/2023 访问量:40
在 Rails 7 中使用多态关联的不允许的参数
Unpermitted Params using Polymorphic Association in Rails 7
问:
根据上图,我做了一个简单的例子。
型号: Person
class Person < ApplicationRecord
belongs_to :personable, polymorphic: true
end
型号: Customer
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,但我没有找到解决它的方法。
答:
0赞
James Hibbard
11/4/2023
#1
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
评论
0赞
Saulinho
11/4/2023
非常感谢詹姆斯。一个星期以来,我一直在寻找解决方案。但是,我只是通知了 :p erson_attributes,它起作用了。
0赞
James Hibbard
11/4/2023
乐于帮助:)如果答案解决了您的问题,如果您能将其标记为已接受,那就太好了。
评论