0

Using rails (4), I would like to parse some data from an external API and store it into my database. For instance:

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

I am aware that with JSON.parse I could create a new instance and store it if the json would match, but there are a few problems that prevent me to do it:

  • commonName uses cammelcase instead of rails typical underscore. Is there a way i can magically assign a key to an attribute?

  • Will vehicles be saved to the table vehicles ? Can I accomplish that automatically? Or should I go through every vehicle and save each one?

  • Components is just an array of strings. What would be a good way to represent that? Just another table with an attribute name?

1 Answer 1

2

Yes, if you want to be able to look up the components then having it as a separate table makes sense. It would need a vehicle_id as well as name.

For accepting the attributes for the vehicles and components use accepts_nested_attributes_for.

So your models should looked something like this:

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

For converting commonName (camelCase) to common_name (snake case), there's a great Stack Overflow answer on that here: Converting nested hash keys from CamelCase to snake_case in Ruby. So assuming you have defined the function described there (convert_hash_keys) and the models above, your code should look roughly like this:

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

For updating it would be VehicleType.update(converted_hash)

Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks for the answer! But about serialize components, with this it's not very easy to look up for vehicles with a concrete component, and you're storing quite some duplicate data
That makes sense. I updated the answer for the case when components is a table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.