我正在使用代码:
<%= image_tag site.photo.url(:small) if site.photo.file? %>
如果没有与特定帖子相关的照片(在这种情况下是网站),则告诉我的应用不显示任何内容。有没有办法用这个来呈现消息。例如“没有帖子的图像”。我只是尝试了
<%= if site.photo.file? %>
<p> no image with this site </p>
<% end %>
但这似乎不起作用。如果你不知道的话,新的红宝石和铁轨。
答案 0 :(得分:4)
当有照片时,您的代码会输出no image with this site
。请改用:
<% unless site.photo.file? %>
<p> no image with this site </p>
<% end %>
甚至更好:
<% if site.photo.file? %>
<%= image_tag site.photo.url(:small) %>
<% else %>
<p> no image with this site </p>
<% end %>
答案 1 :(得分:2)
一个真正简单的方法是创建一个小帮手:
def show_photo_if_exists(photo)
photo.file? ? image_tag photo.url(:small) : "No image with this site"
end
然后在您的视图中致电:
<%= show_photo_if_exists(site.photo) %>
答案 2 :(得分:1)
<%= image_tag(site.photo.url(:small)) rescue "<p>No image</p>" %>
答案 3 :(得分:1)
你是在正确的轨道上,但是只有在site.photo.file中你想要显示它时缺少一些逻辑?返回false,因此您需要在视图中使用它:
<%= if !site.photo.file? %>
<p> no image with this site </p>
<% end %>
(请注意在site.photo.file前面的爆炸!这将反转逻辑。)