2

I am new to RoR

I know how to upload a CSV file into my database, but the CSV file which I have is in a weird format, instead of headers in a header column, the header is in front of the data like this:

Name:Peanut,Age:17,State:NY
Name:Donkey,Age:23,State:NY
Name:Flower,Age:18,State:NY

Another problem is some rows don't have all the data so isn't in the same order like this:

Name:Peanut,Age:17,State:NY
Name:Donkey,State:NY
Age:18,State:NY

I guess I would use a loop in the model file to first extract the header but don't have an idea on where to start nor how it should look. Please help?

2
  • are the headers the same values as your database? Commented Jan 7, 2015 at 13:55
  • @Anthony yes, they are Commented Jan 7, 2015 at 13:55

1 Answer 1

2

When you create objects, you really just pass in a hash of values like this:

User.create(name: "Some name", age: 18)

You can use a ruby script like this:

require 'CSV'
CSV.foreach('users.csv') do |line|
  user = line.each_with_object({}) do |val, hash|
    vals = val.split(':')
    hash[vals.first] = vals.last
  end
  User.create(user)
end

I'm just building a hash of values that look like this:

{"Name"=>"Peanut", "Age"=>"17", "State"=>"NY"}
{"Name"=>"Donkey", "Age"=>"23", "State"=>"NY"}
{"Name"=>"Flower", "Age"=>"18", "State"=>"NY"}

I'm sending those values into the User.create call. Regarding your missing data, it would only be a problem if you have validations on your model (ie. validates :age, presence: true) otherwise, if you don't give it a value it will just be nil in your database (which would be accurate if you're not being provided the data).

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

Comments

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.