从Rails导出CSV数据 [英] Exporting CSV data from Rails
问题描述
我正在从rails导出csv数据。我在这里遵循教程: http://railscasts.com / episodes / 362-exporting-csv-and-excel?view = asciicast
I'm working to export csv data from rails. I'm following the tutorial here: http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast
在我的控制器中,我有:
In my controller I have:
def show
# @company is being provided correctly.
@groups = @company.groups
render text: @groups.to_csv
end
b $ b
在我的group.rb模型中:
In my group.rb model:
def self.to_csv
Rails.logger.info "Hello World"
CSV.generate do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
问题是浏览器只输出以下内容:
The issue is the browser is outputting just the following:
#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#,#
即使在rails重新启动后,模型方法也被忽略。任何想法在这里错了什么?感谢
The model method appears to be being ignored, even after a rails restart. Any ideas what's wrong here? Thanks
推荐答案
to_csv
是类方法。这意味着它被称为 Group.to_csv
。您可能希望将方法签名更改为 Group.to_csv(groups)
。
The to_csv
is a class method. Meaning its meant to be called like Group.to_csv
. You might want to change the method signature to something like Group.to_csv(groups)
instead.
def self.to_csv(groups)
Rails.logger.info "Hello World"
CSV.generate do |csv|
csv << column_names
groups.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
然后在 show
def show
# @company is being provided correctly.
@groups = @company.groups
render text: Group.to_csv(@groups)
end
这篇关于从Rails导出CSV数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!