Rails:文件名中的 image_tag 助手/元音变音会在生产中引发错误
我正在 Heroku 上的 Rails 3 应用程序中通过 dragonfly 上传文件名包含元音变音的图像。然后我尝试使用在开发中显示图像,
image_tag @model.image.url, …
一切正常,但在生产中我得到:
incompatible character encodings: UTF-8 and ASCII-8BIT
.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.7/lib/action_view/helpers/tag_helper.rb:129:in `*'
阅读了一些内容后,我
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
在 environment.rb
中添加了内容,但问题仍然存在。
解决这个问题的正确方法是什么?上传时我必须修正文件名吗?我的印象是这在 Rails 3 中应该可以正常工作?
I am uploading an image with a file name containing an umlaut via dragonfly in a Rails 3 app on Heroku. Then I'm trying to display the image using
image_tag @model.image.url, …
In development everything works just fine, but in production I'm getting:
incompatible character encodings: UTF-8 and ASCII-8BIT
.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.7/lib/action_view/helpers/tag_helper.rb:129:in `*'
After reading a bit I've added
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
in environment.rb
but the problem remains.
What is the proper way to go about this? Do I have to fix the file name when uploading? I was under the impression this should work just fine in Rails 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您可以尝试类似
url.force_encoding('utf8')
您也可以在将模型保存到数据库之前简单地清理模型中的 url - 这就是我所做的。是的,我有时也会在最奇怪的地方偶然发现这一点。
这就是我的模型的样子:
这将用 ASCII 对应项替换德语变音符号,将空格转换为下划线并删除其他所有内容。
第一行
#encoding: UTF-8
很重要,否则 ruby 会抱怨 model.rb 文件中存在非 ASCII 字符...Well, you could try something like
url.force_encoding('utf8')
You could also simply sanitize the url in the model before saving it to the database - that's what I did. And, yes, I sometimes stumble over this in the weirdest places, too.
This is what my model looked like:
This will replace the German umlaute with their ASCII counterparts, convert spaces to underscores and drop everything else.
The first line
# encoding: UTF-8
is important or ruby will complain of non-ASCII characters in the model.rb file...除了 @Rhywden 的答案之外,这里还有我针对 Dragonfly 的解决方案:
详细信息请参见 http://markevans .github.com/dragonfly/file.Models.html 和此处 http://guides.rubyonrails.org/security.html#file-uploads 。
In addition to @Rhywden's answer, here my solution specific for Dragonfly:
Details here http://markevans.github.com/dragonfly/file.Models.html and here http://guides.rubyonrails.org/security.html#file-uploads .