Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 ActiveRecord::SerializationTypeMismatch while creating a resource via API

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"]
  }
}
like image 695
Sambhav Sharma Avatar asked Oct 26 '25 09:10

Sambhav Sharma


1 Answers

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
like image 62
Sambhav Sharma Avatar answered Oct 28 '25 23:10

Sambhav Sharma