在Ruby on Rails中将表读入数组 [英] Read a table into an array in Ruby on Rails
本文介绍了在Ruby on Rails中将表读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用RoR 4和SQlite3进行开发,使用mySQL进行生产.
Using RoR 4, and SQlite3 for development, mySQL for production.
给出一个表格"Things":
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"]]
推荐答案
刚刚:
my_array = MyModel.select(:position, :name, :value, :code).map {|e| e.attributes.values}
我认为它可以解决问题.
I think it does the trick.
已编辑
如果要所有字段:
my_array = MyModel.all.map {|e| e.attributes.values}
如果您希望每一行都是哈希:
If you want each row to be a Hash:
my_array = MyModel.all.to_a
这篇关于在Ruby on Rails中将表读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文