Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

Convert array of JSON to array of Activerecord models?

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

My current code looks like this, and I'd to not iterate 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

Upvotes: 4

Views: 2902

Answers (1)

bjhaid
bjhaid

Reputation: 9752

You should do:

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

where Klass is the ActiveRecord model class

EDIT

Based on the comments, you don't want to mass assign ID's, it could really get clumsy, it's better to leave rails to generate it for you, non mass assignment is:

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

:id, "id" is because I am not sure if the parsed JSON uses symbol or strings as keys

Upvotes: 3

Related Questions