解析嵌套 JSON 并使用 rails 将其保存到数据库

Parse nested JSON and save it to the database with rails

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

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

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

是的,如果您希望能够查找 components,那么将其作为单独的 table 是有意义的。它需要 vehicle_id 以及 name.

要接受 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(驼峰式)转换为 common_name(蛇形),这里有一个很棒的 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)