【问题标题】:Parse nested JSON and save it to the database with rails解析嵌套的 JSON 并使用 rails 将其保存到数据库
【发布时间】:2015-02-13 17:01:47
【问题描述】:

使用 rails (4),我想从外部 API 解析一些数据并将其存储到我的数据库中。例如:

{ "name" : "Mercedes-Benz",
  "commonName: "Mercedes",
  "vehicles" : [ {
    "name" :  "Mercedes c5",
    "components" : ["wheels", "doors"]
  }]
}

我知道使用 JSON.parse 我可以创建一个新实例并在 json 匹配时存储它,但是有一些问题阻止我这样做:

  • commonName 使用 cammelcase 而不是 rails 典型的下划线。有没有办法可以神奇地将键分配给属性?

  • vehicles 是否会保存到表 vehicles 中?我可以自动完成吗?还是我应该检查每一辆车并保存每一辆车?

  • Components 只是一个字符串数组。什么是代表它的好方法?只是另一个具有name 属性的表?

【问题讨论】:

    标签: ruby-on-rails ruby json parsing ruby-on-rails-4


    【解决方案1】:

    是的,如果您希望能够查找components,那么将其作为单独的表是有意义的。它需要vehicle_idname

    要接受vehiclescomponents 的属性,请使用accepts_nested_attributes_for

    所以你的模型应该是这样的:

    class VehicleType < ActiveRecord::Base
      has_many :vehicles
    
      accepts_nested_attributes_for :vehicles
    end
    
    class Vehicle < ActiveRecord::Base
      belongs_to :vehicle_type      
      has_many :components
    
      accepts_nested_attributes_for :components
    end
    
    class Component < ActiveRecord::Base
      belongs_to :vehicle
    end
    

    为了将 commonName (camelCase) 转换为 common_name (snake case),这里有一个很好的 Stack Overflow 答案:Converting nested hash keys from CamelCase to snake_case in Ruby。所以假设你已经定义了那里描述的函数 (convert_hash_keys) 和上面的模型,你的代码应该大致如下所示:

    converted_hash = convert_hash_keys(JSON.parse(input_json_string))
    vehicle_type = VehicleType.create(converted_hash)
    

    如需更新,则为 VehicleType.update(converted_hash)

    【讨论】:

    • 您好,谢谢您的回答!但是关于序列化组件,用这个来查找具有具体组件的车辆并不容易,并且您存储了很多重复的数据
    • 这是有道理的。我更新了components 是表格时的答案。
    猜你喜欢
    • 2019-06-30
    • 2017-06-16
    • 1970-01-01
    • 2013-02-22
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    相关资源
    最近更新 更多