1

Using RoR 4, and SQlite3 for development, mySQL for production.

Given a table "Things":

POSITION    NAME     VALUE     CODE
1           Animal   Dog       1
1           Animal   Cat       2
1           Animal   Bird      3
2           Place    USA       1
2           Place    Other     2
3           Color    Red       a
3           Color    Blue      b
3           Color    Orange    c
4           Age      Young     a
4           Age      Middle    b
4           Age      Old       c
5           Alive    Yes       y
5           Alive    No        n

How can I read the table into an array that looks like this:

a = [["1", "Animal", "Dog", "1"],
     ["1", "Animal", "Cat", "2"],
     ["1", "Animal", "Bird", "3"],
     ["2", "Place", "USA", "1"],
     ["2", "Place", "Other", "2"],
     ["3", "Color", "Red", "a"],
     ["3", "Color", "Blue", "b"],
     ["3", "Color", "Orange", "c"],
     ["4", "Age", "Young", "a"],
     ["4", "Age", "Middle", "b"],
     ["4", "Age", "Old", "c"],
     ["5", "Alive", "Yes", "y"],
     ["5", "Alive", "No", "n"]] 

2 Answers 2

2

Just:

my_array = MyModel.select(:position, :name, :value, :code).map {|e| e.attributes.values}

I think it does the trick.

Edited

If you want all the fields:

my_array = MyModel.all.map {|e| e.attributes.values}

If you want each row to be a Hash:

my_array = MyModel.all.to_a
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Is there a way to allow for undetermined columns? For example if I added an additional column at a later time, could this code simply pull all columns without hard coding each one?
0

You can have a try.

ActiveRecord::Base.connection.execute('select * from table').map{ |row| row }

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.