Reputation: 22515
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
Reputation: 9752
You should do:
models = jsons.compact.map { |json| Klass.new(JSON.parse(json)) }
where Klass
is the ActiveRecord model class
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