How to render hash
Closed this issue · 3 comments
So I have this basic configuration hash as follows
{
footer_text: 'CopyRight',
footer_color: '#FFF',
footer_logo: '#s3_image_path'
}
Now I want to send this hash as a json using JSONAPI. But every time I am getting error while rendering this. Tried with adding a serializer also but that didn't worked. Here is complete code.
What am I missing here or how can I render a hash using JSONAPI in rails?
Thanks in advance
@sudeeptarlekar you'll have more luck on the gitter https://gitter.im/jsonapi-rb/Lobby
The issue here is that unless otherwise specified, the library will look for a class named SerializableClassName, see the default class configuration.
You could either make a Configuration class/struct to expose those attributes, or specify in the controller endpoint:
render jsonapi: { ... }, class: { Hash: ConfigurationSerializer }The latter approach will likely be more scalable
@gmkohler thanks for inputs but even passing Hash with class argument will result in 500 error as serialiser will look for id. So I ended up using dummy class and wrapped the config hash inside that dummy hash as shown below.
class ConfigurationsController < ApiController
def index
render jsonapi: OpenStruct.new(id: '', configuration: { 'footer-logo': '#FFF' }),
class: { OpenStruct: ConfigurationResponseSerializer }
end
end
class ConfigurationResponseSerializer < JSONAPI::Serializable::Resource
type 'configuration'
attributes :configuration
end
Also, found weird thing that when I use string keys for class option in controller while sending the json data, then it raises 500 error with UndefinedSerializableClass error. Example show below.
render jsonapi: OpenStruct.new(id: '', configuration: { 'footer-logo': '#FFF' }),
class: { 'OpenStruct' => ConfigurationResponseSerializer }
Closing this issue as this is resolved.