Converting a JSON array to an array of Activerecord models?

I have an array of JSON strings. How to convert them to an array of Activerecord models?

My current code looks like this and I will not repeat it one by one:

jsons = ['{"id": 1, "field1" : "value1"}'] #this is an array of jsons
models = [] #i want an array of models back

jsons.each do |json|
            if(json == nil)
                next
            end

            begin
                hash = JSON.parse(json)
            rescue
                next
            end

            model = className.new
            model.attributes = hash
            model.id = hash["id"]
            models << model
end
+4
source share
1 answer

You should:

models = jsons.compact.map { |json| Klass.new(JSON.parse(json)) }

where Klass-ActiveRecord model class

EDIT

Based on the comments, you do not want to assign identifiers in bulk, this can really become awkward, it is better to leave the rails to generate it, rather than in bulk:

models = jsons.compact.map { |json| Klass.new(JSON.parse(json).except(:id, "id")) }

:id, "id" is that I'm not sure if the parsed JSON uses characters or strings as keys

+3
source

All Articles