我正在使用 ruby csv 库。当我尝试下载多条记录时,它工作正常并下载 CSV 文件中的所有记录。
@assets = Asset.all
respond_to do |f|
f.html
f.csv { send_data @assets.to_csv }
f.xls { send_data @assets.to_csv(col_sep: "\t") }
end
但是当我尝试下载单个记录时。它给出了错误
undefined method `to_csv'
这是我的单个记录的代码。
@assets = Asset.last
respond_to do |f|
f.html
f.csv {
send_data @assets.to_csv
}
end
这是我的 to_csv 代码
def self.to_csv(options = {})
CSV.generate(options) do |f|
f << column_names
all.each do |asset|
f << asset.attributes.values_at(*column_names)
end
end
end
最佳答案
这里的问题是应该在ActiveRecord
集合而不是单个记录上调用to_csv
方法。
我相信您遇到的错误一定是
NoMethodError: undefined method `to_csv' for #< Asset:0x0000000xxxx>
改变
@assets = Asset.last
至
@assets = Asset.limit(1).order(id: :desc)
因此,您可以稍微调整代码以将集合传递给 to_csv
并且它将起作用
@assets = Asset.limit(1).order(id: :desc)
respond_to do |f|
f.html
f.csv {
send_data @assets.to_csv
}
end
编辑:
这是一个解决方法,但它确实有效
# If you only want the last record
@assets = Asset.limit(1).order(id: :desc)
# If you know the id or a specific condition
@assets = Asset.where(id: 1).limit(1)
关于ruby-on-rails - 在 Rails 中下载 CSV 格式的单个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42252919/