如何将表作为数组数组获取,其中每个子数组都是一列(而不是一行) [英] How to get table as array of arrays where each sub array is a column (not a row)
本文介绍了如何将表作为数组数组获取,其中每个子数组都是一列(而不是一行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此答案显示了如何将 rails 表作为数组的数组返回按行.如何实现列明智,即每个子数组都是表中的一个列/属性?
This answer shows how to return a rails table as an array of arrays row wise. How can this be achieved column wise, that is, where each of the sub arrays is a column/attribute from the table?
作为参考,这里是如何将表作为数组逐行返回
For reference, here's how to return the table as array of arrays row wise
my_array = Mymodel.all.map {|e| e.attributes.values}
推荐答案
这个有效,调用 SELECT
n 次 (n = Mymodel.column_names.count)
This one works, calls SELECT
n times (n = Mymodel.column_names.count)
my_array = Mymodel.column_names.map { |column| Mymodel.all.map(&column.to_sym) }
这将调用 SELECT column_name
而不是 SELECT *
n 次
This one will call SELECT column_name
instead of SELECT *
n times
my_array = Mymodel.column_names.map { |column| Mymodel.pluck(column.to_sym) }
更好更快的解决方案是这个答案
这篇关于如何将表作为数组数组获取,其中每个子数组都是一列(而不是一行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文