Rails3 CSV 将“”放入而不是实际的报价
与此问题类似,除了我在整个项目的任何地方都没有使用 html_safe
。
我在 index.csv.erb
中生成了一个 CSV 文件,如下所示:
<%=
response.content_type = 'application/octet-stream'
CSV.generate do |csv|
@persons.each do |person|
csv << [ person[:name], person[:nickname] ]
end
end
%>
问题:如果数据库 (ActiveRecord/MySQL) 中的昵称为 NULL,则 CSV 文件关联元素将变为 ""
。我希望""
,或者什么都没有。
结果文件示例:
Nicolas, Nico
Joe, ""
如何防止这种情况发生?
Similar to this question except I don't use html_safe
anywhere in the whole project.
I generate a CSV file in index.csv.erb
like this:
<%=
response.content_type = 'application/octet-stream'
CSV.generate do |csv|
@persons.each do |person|
csv << [ person[:name], person[:nickname] ]
end
end
%>
PROBLEM: If nickname is NULL in the database (ActiveRecord/MySQL) then the CSV file associated element becomes ""
. I would expect ""
, or even nothing at all.
Result file sample:
Nicolas, Nico
Joe, ""
How can I prevent this from happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题是您没有使用
html_safe
。您的昵称字段为空,并在 csv 文件中转换为""
,但 Rails 认为它不安全,并且 html 转义了。只需对结果调用
html_safe
即可:您链接到的解决方案不再适用于 Rails 3,因为默认情况下所有字符串都被视为不安全,而 Rails 2 中的情况并非如此。
The problem here is that you're not using
html_safe
. Your nickname field is blank and converted to""
in the csv file, but it is deemed unsafe by Rails and html escaped.Just call
html_safe
on the result:The solution you linked to does not work anymore with Rails 3 because all strings are considered unsafe by default, which was not the case in Rails 2.
重构的
Benoit 绝对正确,感谢您的提示。查看您的代码后,我还发现了一种更简洁的生成 CSV 的方法,我想我会为那些登陆这里的人(像我一样!)分享该方法:
本质上,您不需要所有 CSV 生成的东西。 Ruby 可以获取
Array
并将其转换为 CSV 字符串,然后只需使用collect
和join
将它们很好地组合在一起。如果您喜欢将其放在单独的行上,您也可以执行以下操作(我就是这么做的):
在这里,您需要使用
-%>
来确保不会出现额外的空行,并且您 可以需要使用row_sep: nil
选项,以便to_csv
不会在每行末尾添加\n
。不管怎样,希望能帮助清理一些人的代码。
Refactored
Benoit is absolutely correct and thanks for that tip. After looking at your code I see a much cleaner approach to generating your CSV as well, which I thought I would share for those landing here (like me!):
Essentially, you don't need all that CSV generate stuff. Ruby can take an
Array
and turn it into a CSV string, then just use acollect
andjoin
to put it all together nicely.You can also do the following if you prefer having it on separate lines, which I do:
Here you'll need to use the
-%>
to ensure you don't get extra blank lines and you'll need to use therow_sep: nil
option so thatto_csv
doesn't add a\n
at the end of each line.Anyway, hope that helps clean some people's code up.