[英]Ruby on Rails export to csv - maintain mysql select statement order
Exporting some data from mysql to a csv file using FasterCSV. 使用FasterCSV将一些数据从mysql导出到csv文件。 I'd like the columns in the outputted CSV to be in the same order as the select statement in my query.
我希望输出的CSV中的列与查询中的select语句的顺序相同。
Example: 例:
rows = Data.find(
:all,
:select=>'name, age, height, weight'
)
headers = rows[0].attributes.keys
FasterCSV.generate do |csv|
csv << headers
rows.each do |r|
csv << r.attributes.values
end
end
CSV Output: CSV输出:
height,weight,name,age
74,212,bob,23
70,201,fred,24
.
.
.
I want the CSV columns in the same order as my select statement. 我希望CSV列的顺序与我的select语句相同。 Obviously the attributes method is not going to work.
显然,attributes方法不会起作用。 Any ideas on the best way to ensure that the columns in my csv file will be in the same order as the select statement?
关于确保我的csv文件中的列与select语句的顺序相同的最佳方法的任何想法? Got a lot of data and performance is an issue.
有大量数据,性能是一个问题。 The select statement is not static.
select语句不是静态的。 I realize I could loop through column names within the rows.each loop but it seems kinda dirty.
我意识到我可以遍历row.each循环内的列名,但似乎有点脏。
class Data < ActiveRecord:Base
comma do
name
age
height
weight
end
comma :height_weight do
name
age
height_in_feet
weight
end
end
Now you can generate the CSV as follows: 现在,您可以按以下方式生成CSV:
Data.all(:select => 'name, age, height, weight').to_comma
Data.all(:select => 'name, age, height_in_feet, weight').to_comma(:height_weight)
Edit: 编辑:
The ActiveRecord finders does not support calculated columns in the resultset, ie ActiveRecord查找器不支持结果集中的计算列,即
data = Data.first(:select => 'name, age, height/12 as height_in_feet, weight')
data.height_in_feet # throws error
You can use select_extra_columns gem if you want to include the calculated columns. 如果要包括计算列,则可以使用select_extra_columns gem。
Try this: 尝试这个:
def export_to_csv (rows, col_names)
col_names = col_names.split(",") if col_names.is_a?(String)
FasterCSV.generate do |csv|
# header row
csv << col_names
# data rows
rows.each do |row|
csv << col_names.collect{|name| row.send(name)}
end
end
end
cols = 'name, age, height, weight'
rows = Data.find(:all, :select=> cols)
csv = export_to_csv(rows, cols)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.