我正在使用Rails 5(beta3)API应用程序。我的模型有一个序列化属性,序列化为一个数组。当我从邮递员发送测试请求时,我收到以下错误:
ActiveRecord::SerializationTypeMismatch (Attribute was supposed to be a Array, but was a String. -- "[\"amat\",\"bmat\",\"cmat\"]"):
app/controllers/api/v1/services_controller.rb:23:in `create'
Rendered vendor/cache/gems/actionpack-5.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (3.1ms)
Rendered vendor/cache/gems/actionpack-5.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.3ms)
Rendered vendor/cache/gems/actionpack-5.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.8ms)
Rendered vendor/cache/gems/actionpack-5.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (15.3ms)
我理解错误的含义,但我无法序列化从post请求中获得的数据。在尝试创建请求之前,我不知道如何或在哪里序列化。
我的控制器的相关部分:
before_action :set_service, only: [:show, :edit, :update, :destroy]
def create
@service = Service.new(service_params)
if @service.save
render json: {message: 'Service created.'}, status: 200
else
render json: {message: 'Error creating Service.'}, status: 500
end
end
private
def set_service
@service = Service.find(params[:id])
end
def service_params
params.require(:service).permit(:name, :sub_service, :material, :parts)
end
服务模式:
class Service < ApplicationRecord
serialize :parts,Array
end
我发送请求为Raw JSON:
{
"service" : {
"name": "Foiling",
"sub_service":"Full",
"material":"plastic",
"parts":["parta","partb","partc"]
}
}
答案 0 :(得分:2)
我想通了,我需要明确告诉rails期望在params中使用数组:
def service_params
params.require(:service).permit(:name, :sub_service, :material, :parts => [])
end