加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 将JSON数组转换为Activerecord模型数组?

发布时间:2020-12-17 02:21:56 所属栏目:百科 来源:网络整理
导读:我有一个 JSON字符串数组.如何将它们转换为Activerecord模型数组? 我当前的代码看起来像这样,我不会一个接一个地迭代它: jsons = ['{"id": 1,"field1" : "value1"}'] #this is an array of jsonsmodels = [] #i want an array of models backjsons.each do
我有一个 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是否使用符号或字符串作为键

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读