1

I have a Rails backend using postgresql jsonb field. I would like to use the gem fast_jsonapi but am not married to it.

I have a jsonb field that is pretty much the model I want to serialize. However, I haven't figured out how to make json attributes of them (serialize them as first class citizens.) So, instead of:

{  
   "attributes":{  
      "data":{  
         "title":"ok",
         "author":"masta p"
      },
      "created_at":"2019-02-16T17:40:21.477Z",
      "updated_at":"2019-02-16T17:40:21.477Z"
   }
}

I don't need the extra 'data' namespace and would like it to be:

{  
   "attributes":{  
      "title":"ok",
      "author":"masta p"
      "created_at":"2019-02-16T17:40:21.477Z",
      "updated_at":"2019-02-16T17:40:21.477Z"
   }
}

What's a low cost way of doing this?

1 Answers1

1

For fast_jsonapi this is not possible. Every attribute declared in serializer class are dispatched to active record object. You would see here how the the library serializes the given object.

So if you want to serialize jsonb objects as first citizen I think you have 2 ways. First, you would extend FastJsonapi::Attribute class and then override the serialize method. But I do not recommend this way due to the fact that this is really error prone.

The second way is explicitly declaring fields from the jsonb object. For istance, the following workaround would fit your problem I think.

class TestSerializer
  include FastJsonapi::ObjectSerializer

  JSONB_ATTRIBUTES = %i[title author review_count]
  JSONB_ATTRIBUTES.each do |attr|
    attribute attr do |object|
      object.data[attr.to_s] if object.data # Protection againts nil value
    end
  end
end

This is much more better than extending the serializer class.

zeitnot
  • 1,304
  • 12
  • 28