[英]Rails create model along with associated data from JSON
I have a RESTful create action in my Rails API for my model Case
. 我在我的模型Case
Rails API中有一个RESTful创建动作。 It's very simple: 很简单:
@case = Case.new(case_params)
if @case.save
render json: @case, status: :created, location: @case
else
render json: @case.errors, status: :unprocessable_entity
end
I am POSTing data to the endpoint (JSON) with the fields for the model as well as associations. 我正在使用模型的字段以及关联将数据发布到端点(JSON)。 When the form is filled out on the frontend, addresses are included. 在前端填写表格时,将包括地址。 The Case
model has many Address
models. Case
模型具有许多Address
模型。
So I include the addresses in the JSON as an array of objects, ex: 因此,我将地址包含在JSON中作为对象数组,例如:
{
"field_on_case": "value",
"addresses": [{
"street_address": "1234 wonderland"
}, {
"street_address": "4321 wonderland"
}]
}
When doing this, and POSTing to the API, in the web server I see: Unpermitted parameters: addresses
在执行此操作并发布到API时,在Web服务器中,我看到: Unpermitted parameters: addresses
I have this snippet in my Case
controller in the case_params
method: 我有这样的片段在我的Case
在控制器case_params
方法:
params.require(:case).permit(:addresses, addresses_attributes: [:id, :type, :street_address, :city, :zip, :state])
I also have this line in my Case
model: 我的Case
模型中也有以下一行:
accepts_nested_attributes_for :addresses
If an attribute is a hash you need to specify this: 如果属性是哈希,则需要指定以下内容:
addresses: [ ]
in your params. 在您的参数中。 I think you can use: 我认为您可以使用:
params.require(:case).permit(addresses: [:type, :street_adress, :city, :zip, :state])
And then you can remove the nested_attribute from your model as well. 然后,您也可以从模型中删除nested_attribute。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.