解析嵌套 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
创建一个新实例并存储它,但是有一些问题阻止我这样做:
commonName
使用 cammelcase 而不是 rails 典型的下划线。有没有一种方法可以神奇地将键分配给属性?
会不会vehicles
保存到tablevehicles
?我可以自动完成吗?还是我应该检查每一辆车并保存每一辆车?
Components 只是一个字符串数组。什么是表示它的好方法?另一个 table 属性为 name
?
是的,如果您希望能够查找 components
,那么将其作为单独的 table 是有意义的。它需要 vehicle_id
以及 name
.
要接受 vehicles
和 components
的属性,请使用 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)
使用 rails (4),我想从外部 API 解析一些数据并将其存储到我的数据库中。例如:
{ "name" : "Mercedes-Benz",
"commonName: "Mercedes",
"vehicles" : [ {
"name" : "Mercedes c5",
"components" : ["wheels", "doors"]
}]
}
我知道如果 json 匹配,我可以使用 JSON.parse
创建一个新实例并存储它,但是有一些问题阻止我这样做:
commonName
使用 cammelcase 而不是 rails 典型的下划线。有没有一种方法可以神奇地将键分配给属性?会不会
vehicles
保存到tablevehicles
?我可以自动完成吗?还是我应该检查每一辆车并保存每一辆车?Components 只是一个字符串数组。什么是表示它的好方法?另一个 table 属性为
name
?
是的,如果您希望能够查找 components
,那么将其作为单独的 table 是有意义的。它需要 vehicle_id
以及 name
.
要接受 vehicles
和 components
的属性,请使用 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)