In my code, I am trying to dynamically instantiate an ActiveRecord Model from JSON. The sample Json is:
{"id":10,"name":"XYZ"}
When I try to instantiate from Ruby:
file_name = "json_file.json"
method = "name"
klass = Kernel.const_get(method.classify)
json = File.read(file_name)
instance = klass.new.from_json(json)
But when the instance is created of type Name
, it does not include the id
value from the JSON. It's nil, while I want it to be 10 as specified.
If I try to insert instance.save!
then it creates a new ID everytime, which is not what I want.
What could be the reason?