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.