我有一个 JSON 字符串数组。如何将它们转换为 Activerecord 模型数组?
我当前的代码如下所示,我不想一一重复:
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
最佳答案
你应该这样做:
models = jsons.compact.map { |json| Klass.new(JSON.parse(json)) }
其中 Klass
是 ActiveRecord 模型类
编辑
根据评论,您不想批量分配 ID,它真的会变得笨拙,最好让 rails 为您生成它,非批量分配是:
models = jsons.compact.map { |json| Klass.new(JSON.parse(json).except(:id, "id")) }
:id, "id"
是因为我不确定解析出来的json是用symbol还是strings作为key
关于ruby-on-rails - 将 JSON 数组转换为 Activerecord 模型数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21220488/