"ActionView :: Template :: Error(未预编译)"在"image_tag nil"上引发 [英] "ActionView::Template::Error ( isn't precompiled)" raised on "image_tag nil"
问题描述
如果我不能正确处理视图,生产环境将显示500.
If I don't handle view correctly, Production environment show 500.
<%= image_tag post.user.image_url %>
可能是
<%= image_tag post.user.image_url if post.user && post.user.image_url %>
但是我有点粗心,忘记了几次这个问题.
but I am little careless and forgot this issue several times.
如何防止这种情况?如何在生产环境中使用<%= image_tag nil %>
而不提高500?
How can I prevent this? How can I use <%= image_tag nil %>
in production environment without raising 500?
推荐答案
image_tag
必须有一个源,Rails不能执行任何操作,但是会引发异常.
image_tag
must have a source, Rails can do nothing with it, but raise an exception.
您可以像这样编写一个助手:
You can write a helper like this:
module ApplicationHelper
def safe_image_tag(source, options = {})
source ||= "default.jpg"
image_tag(source, options)
end
end
或直接在视图中直接检查nil
.无论如何,您都必须做些 来防止错误.
or simply check for nil
directly in a view. Anyway you have to do something to prevent an error.
这篇关于"ActionView :: Template :: Error(未预编译)"在"image_tag nil"上引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!