Deserialize ActiveRecord from JSON

放肆的年华 提交于 2019-12-04 18:18:53

You could instantiate the new object from JSON and then assign the id afterwards. Probably best to create your own method for this:

class Model
  def self.from_json_with_id(params = {})
    params = JSON.parse(params)
    model = new(params.reject {|k,v| k == "id"})
    model.id = params["id"]
    model
  end
end

Or maybe just override the from_json() method.

Why not like this:

JSON.parse(@json_string).each do |item|
     item.delete(:id) # I tested it in my case it also works without this line
     object=Model.create(item)
end

If the host that created the JSON adds a JSON root you might have to use item[1] instead of item.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!