Read a table into an array in Ruby on Rails

2019-08-06 23:59发布

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条回答
倾城 Initia
2楼-- · 2019-08-07 00:22

You can have a try.

ActiveRecord::Base.connection.execute('select * from table').map{ |row| row }
查看更多
不美不萌又怎样
3楼-- · 2019-08-07 00:37

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
查看更多
登录 后发表回答