airsoftFreak
airsoftFreak

Reputation: 1608

Convert JSON back to ActiveRecord

So currently I have a Model class

class Book
  # author_id
end

I have a simple delegator class for the Model class above

class BookDecorator < SimpleDelegator
   attr_accessor :list_of_reviews
   
   def initialize
      super
      @list_of_reviews = []
   end
end

I tested it on Rails Console

-> book = Book.find(1)
-> book = BookDecorator(book)
-> book.list_of_reviews  
-> []

However when I serialize the object to JSON

-> book = book.to_json
-> Deserialize back
-> book = JSON.parse(book)
-> book.list_of_reviews
-> NoMethodError: undefined method `list_of_reviews` for <String:0x00007>

How do I deserialize the JSON back to ActiveRecord with the decorator attached?

The reason why I have to serialize to JSON because I have to store it in Redis.

And deserialize later to access that list_of_reviews method

Upvotes: 2

Views: 861

Answers (1)

max
max

Reputation: 102443

There is no automatic way of "deserializing" a record back from JSON. Its a one way process. A very naive solution would be:

book = Book.new(JSON.parse(book))

However the record will not behave like a record that has been persisted and fetched from the database which can cause issues.

There is also the issue that you're casting the attributes of a record to the primitive types supported by JSON. One example of this is that JSON does not have a proper decimal type which can cause rounding errors and that associations won't be serialized/deserialized.

This entire endavor seems very much like a wild goose chase as Rails has tons of caching mechanisms already to solve most problems.

Upvotes: 4

Related Questions