I am using Rails 5 (beta3) application for APIs. My model has a serialized attribute, serialized to an array. When I am sending a test request from Postman, I get the following error:
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)
I understand what the error means, but I am unable to serialize the data I get from the post request. I don't know how or where to serialize this before attempting a create request.
Relevant parts of my controller:
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
Service Model:
class Service < ApplicationRecord
serialize :parts,Array
end
I am sending the request as Raw JSON:
{
"service" : {
"name": "Foiling",
"sub_service":"Full",
"material":"plastic",
"parts":["parta","partb","partc"]
}
}
I figured it out, I need to explicitly tell rails to expect for an array in params:
def service_params
params.require(:service).permit(:name, :sub_service, :material, :parts => [])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With