0

Here is the array data:

data =  [

        # == DB Seeds == 
            ["name", "Peter", "Pan", "Ulla"],
            ["t_u_a", "4405", "6710", "8010"],
            ["t_u_b", "5590", "5590", "9080"]

]

It is column name, value, value, value.

Does Rails have a nice create method for arrays?

Instead of my having to write:

    Product.create([{ name: 'Peter', tu_a_a: '4405', tu_a_b: '5590' },

    { name: 'Pan', tu_a_a: '6710', tu_a_b: '5590'  }, 

    { name: 'Ulla', tu_a_a: '8010', tu_a_b: '9080'  }])

Update:

[{"name"=>"name", "Peter"=>"Peter", "Pan"=>"Pan", "Ulla"=>"Ulla", nil=>nil}, 

{"name"=>"t_u_a", "Peter"=>"4405", "Pan"=>"6710", "Ulla"=>"8010", nil=>nil}, 

{"name"=>"t_u_b", "Peter"=>"5590", "Pan"=>"5590", "Ulla"=>"9080", nil=>nil}]

1 Answer 1

3

You can use the ActiveRecord create function, but first you're need to reformat your data as an array of hashes, instead a 2d array where the first array is the column names. Here is a quick function to do that (if you use this, make sure you test it, because I haven't) -

def convert_to_hashes(my_array)
    keys = my_array.map {|d| d[0]}
    new_array = []
    count = 0

    (1..my_array[0][0].length-1).each do |values|
        new_hash = {}
        count += 1
       (0..keys.length-1).each do |index|
            new_hash[keys[index]] = my_array[index][count]
        end
        new_array << new_hash
    end

    new_array
end

So then you end up with [your model name].create(convert_to_hashes(my_data))

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

5 Comments

I have just tried your solution, have updated my question with the output. The keys are wrong.
Change the keys to my_array.map {|d| d[0]}
I have updated this function to fix the issue you were seeing with the column names being treated as the first value set. This should also take care of the nil key/value at the end. Other than that, however, the values look correct. Also, map is a nicer way of doing it - once you've tweaked out all the bugs, feel free to post the final function for others. But, you get the idea - convert the data and use the create function.
You may also benefit from using inject for the my_array.each loop. Good answer though.
I have a some problems with the values: pastie.org/private/1xqsieperan2zjxqstubta#19

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.