Ruby on rails 替换转置法?
我有以下代码:Ruby on rails 替换转置法?,ruby-on-rails,ruby,arrays,prawn,transpose,Ruby On Rails,Ruby,Arrays,Prawn,Transpose,我有以下代码: table([ ["UnitID", "First Name", "NPS Score", "Comments"], *[invite_unitid_arr, invite_name_arr, nps_score_integers_final, comment_arr] .transpose.reject{ |x| x[3].empty? } ], :position => :center, :colu
table([
["UnitID", "First Name", "NPS Score", "Comments"],
*[invite_unitid_arr, invite_name_arr, nps_score_integers_final, comment_arr]
.transpose.reject{ |x| x[3].empty? }
], :position => :center, :column_widths => {0 => 50, 1 => 60, 2 => 60, 3 => 40, 4 => 150}) do
row(0).style :background_color => 'C0C0C0'
end
我在一个数组上调用转置
。我正在重构这段代码,现在我有了一个模型对象数组:
array = Model.all
我如何重写上面的内容,说“遍历每个模型(模型1、模型2等),并创建一行,其中包含属性unit_id、first_name、nps_score、注释如下:
Model1[:unit_id]、Model1[:first_name]、Model1[:nps_score]
”我不完全确定您想在这里实现什么,但您似乎正在寻找pull
方法。由于rails 4,它允许您一次提取多个列(默认情况下将提取所有列)。看来:
Model.pluck(:unit_id, :first_name, :nps_score, :comment)
这是您正在寻找的—实际上要好得多,因为它不实例化新对象,只对db进行一次调用。它将返回2d数组,每个模型一行。如果您更愿意在同一列中使用不同的值,请在上面添加转置。如果我理解正确,您可以使用如下对象数组:
my_models = [ <MyModel id: 1, unit_id: 123, first_name: "Xxx", nps_score: 100, ...>,
<MyModel id: 2, unit_id: 456, first_name: "Yyy", nps_score: 200, ...>,
...
]
[ [ "UnitID", "First Name", "NPS Score", "Comments" ],
[ 123, "Xxx", 100, "..." ],
[ 456, "Yyy", 200, "..." ],
...
]
您真正需要做的就是:
headers = [ "UnitID", "First Name", "NPS Score", "Comments" ]
data = my_models.map do |model|
[ model.unit_id, model.first_name, model.nps_score, model.comments ]
end
rows = [ headers, *data ]
或者
(无论哪种方式,您都可以将其设置为一行程序,但请注意代码的可读性。)
当然,最好只选择要使用的列,因此您可以这样做(添加所需的where
、order
等调用):
在Rails 4中,该方法采用多个参数,这使得此过程更加简单:
data = MyModel.where(...).pluck(:unit_id, :first_name, :nps_score, :comments)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]
my_models = MyModel.select([ :unit_id, :first_name, :nps_score, :comments ]).where(...)
data = my_models.map(&:attributes)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]
data = MyModel.where(...).pluck(:unit_id, :first_name, :nps_score, :comments)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]