0

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?

Sid
  • 4,893
  • 14
  • 55
  • 110

1 Answers1

0

In Rails, ActiveRecord takes care of assigning record IDs by default, so what is happening is that Rails is ignoring this part "id":10 of your JSON.

What you need to do is override this default behaviour of ActiveRecord (ideally you shouldn't do that), how would you do that I'm not sure, though there might be something you can do about it, check this question out. This post might shed some light on the topic as well. Good luck.

Community
  • 1
  • 1
Karim Tarek
  • 797
  • 4
  • 18
  • Thanks! But I want this object to act as a standalone object, independent of its ActiveRecord underpinnings. – Sid Jun 18 '16 at 15:31
  • You wrote "I am trying to dynamically instantiate an ActiveRecord Model from JSON", right? so if your class inherits from ActiveRecord, then it's defaults applies to your class. – Karim Tarek Jun 18 '16 at 15:35