Search code examples
ruby-on-railsjsonpostgresqlactive-model-serializers

How to use ActiveModel::Serializer with a PostgreSQL JSON column


I am trying to use ActiveModel::Serializer in conjunction with a PostgreSQL database.

The problem I am having is that whenever I include a json type column in a serializer I get:

SystemStackError (stack level too deep):
  actionpack (4.0.0) lib/action_dispatch/middleware/reloader.rb:70

I don't want to do this as I need access to the data before returning it.

From schema.rb:

create_table "jobs", force: true do |t|
    t.integer  "user_id"
    t.string   "tool"
    t.string   "name"
    t.json     "options"
    t.integer  "status"
    t.string   "version"
    t.datetime "created_at"
    t.datetime "updated_at"
end

job_serializer.rb:

class JobSerializer < ApplicationSerializer
    attributes :id, :tool, :name, :status, :options, :version, :created_at

    has_many :inputs, serializer: FileLinkSerializer
end

Works fine if I remove :options from the attributes but crashes when it is included as above.


Solution

  • The problem is with having a field named options. I wrapped that field in a field called called tool_options and everything worked fine.

    class JobSerializer < ApplicationSerializer
      attributes :id, :tool, :name, :status, :tool_options, :version, :created_at
    end
    
    class Job < ActiveRecord::Base
      def tool_options
        options
      end
    end
    

    (In reality I'll be changing my schema as its not too late.)