-1

I am using redis cache for saving data. I am saving data using to_json. How should I get data so that it becomes like before save.

Before save

#<CarModel id: 1, car_make_id: 1, title: "Jazz.....

After get using JSON.load

{"id"=>1, "car_make_id"=>"1",.........}

How I get so it becomes like before

Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133

1 Answers1

0

Your CarModel already includes ActiveModel::Serializers::JSON (assuming it is a usual Rails model), so it responds to as_json which returns the attributes as a (JSON compatible) hash:

car = CarModel.new(id: 1, car_make_id: 1, title: "Jazz")
#=> #<CarModel id: 1, car_make_id: 1, title: "Jazz">

json_object = car.as_json
#=> {"id"=>1, "car_make_id"=>1, "title"=>"Jazz"}

as_json is called by to_json to create a JSON string: (you already use this method)

json_string = car.to_json
#=> "{\"id\":1,\"car_make_id\":1,\"title\":\"Jazz\"}"

from_json on the other hand parses a JSON string:

Car.new.from_json(json_string)
#=> #<CarModel id: 1, car_make_id: 1, title: "Jazz">

Note that Car.new creates a new instance and from_json simply populates its attributes. Any other states will not be serialized.

Furthermore, the object in your database might have been changed in the meantime, so it could be preferable to just store the object's id and fetch a fresh copy from the database instead.

Stefan
  • 109,145
  • 14
  • 143
  • 218
  • did you mean `to_json` instead of `as_json`? – Md. Farhan Memon Jun 30 '17 at 11:35
  • @Md.FarhanMemon no, `ActiveModel::Serializers::JSON` provides `as_json` and `from_json`. But `to_json` probably calls `as_json`. I didn't provide any further details, because that whole "storing active record objects as json in redis" looks a bit suspicious to me. – Stefan Jun 30 '17 at 11:49
  • 1
    `as_json` returns a `Hash` whereas `to_json` returns a `String`, thus they both are different. `from_json` needs `String` to process, when passed `Hash` it throws `TypeError: no implicit conversion of Hash into String`. Infact, the reference you shared for [from_json](http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-from_json) has an example which uses `to_json`.. – Md. Farhan Memon Jun 30 '17 at 11:56
  • @Md.FarhanMemon you are right, I mixed up the methods. `to_json` calls `as_json`, not the other way round. I've updated my answer. Thanks for the heads-up. This happens if you don't try your solutions ;-) – Stefan Jun 30 '17 at 12:01