I want to develop methods for a JSON import/export system.
With a simple example where we have a cat with paws, I made this :
class Cat < ApplicationRecord
has_many :paws
def json_export
json = self.to_json(include: :paws)
File.open("some_file_name.txt", "w") { |file| file.puts json }
end
def self.json_import
Cat.new.from_json(File.open("some_file_name.txt", "rb").read)
end
end
# I put Paw code below FYI
class Paw < ApplicationRecord
belongs_to :cat
end
The JSON present in the file is :
{"id":1,"name":"Felix","paws":[{"id":1,"color":"red","cat_id":1}]}
But when I run json_import I got that error :
ActiveRecord::AssociationTypeMismatch: Paw(#69870882049060) expected, got {"id"=>1, "color"=>"red", "cat_id"=>1} which is an instance of Hash(#47217074833080)
I found nothing in the doc for 'from_json' related to my problem, and I'm not successful neither for finding resources about that. Is there a way to do that without gems? (If I need one I will consider it however).