Skip to content

Serializing a resource to json and then building it back from json #354

Open
@kujma10-zz

Description

@kujma10-zz

Hello,

I have implemented caching logic in Redis for the json api client resource in order to not request external service every time. In my example this resource is called User.

The problem with caching is that if I store the whole User object and if they are many then it is too slow (to write 1000 users already takes ~ 4-5 seconds, same is with reading).

To make it fast I changed it so that instead of writing the object itself - I store the json (converting it with user.to_json, like it is done on active records) and then when reading building the resource back with User.new(ActiveSupport::JSON.decode(user_json)) (again similar to active record).

This approach I thought it worked at first but then I noticed that during this serialisation and deserialisation the roles relationship of the object is lost. After adding this relation with has_many :roles to the model it worked but then the attributes of role e.g name is not there. To sum up - my goal is to have this equality:
User.new(ActiveSupport::JSON.decode(User.first.to_json)) == User.first which is true in case of active record but not true if it is about JsonApiClient::Resource.

Can you please recommend any way to retrieve the same object back from json? If there is none then maybe you could give suggestion for alternative caching solution. Thanks in advance.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions