如何防止在没有与记录相关联的图像时显示调用相关图像的图像标签?
<%= image_tag @agent.avatar.url %>
如果没有与该代理关联的图像,则会向我提供文本“Missing”。 我想先测试是否有可用的图像,然后在测试返回true时呈现上述标记。
更好的方法是,如果没有特定提供图像,则有没有办法指定默认图像?
<%= image_tag @agent.avatar.url %>
如果没有与该代理关联的图像,则会向我提供文本“Missing”。 我想先测试是否有可用的图像,然后在测试返回true时呈现上述标记。
更好的方法是,如果没有特定提供图像,则有没有办法指定默认图像?
我使用以下代码来判断一个模型是否有关联的附件:
<% if @agent.avatar.file? %>
<%= image_tag @agent.avatar.url(:normal) %>
<% else %>
No attachment available!
<% end %>
如果头像有多种尺寸:
has_attached_file :avatar,
:styles => {:small => '30x30#', :large => '100x100#'},
:default_url => '/images/missing_:style.png'
对于Rails 3:
has_attached_file :avatar,
:styles => {:small => '30x30#', :large => '100x100#'},
:default_url => '/assets/images/missing_:style.png'
好的,那么我已经理解其中的一部分。
在模型中指定默认图片。
has_attached_file :avatar, :default_url => '/images/brokers/agents/anonymous_icon.jpg'
减少一些字节:
<% if @agent.avatar? %>
<%= image_tag @agent.avatar.url(:normal) %>
<% else %>
No attachment available!
<% end %>
如果模型中指定了default_url,您可以使用present?方法来检查url是否为默认的或上传的。
<% if @agent.avatar.present? %>
<%= image_tag @agent.avatar.url(:normal) %>
<% else %>
No attachment available!
<% end %>
我以前也遇到过同样的问题,但是通过使用以下方式解决了它:
<% if @post.image.exists? %>
<%= image_tag @post.image.url %>
<% end %>
user.photo.exists?(:medium).