【问题标题】:How show hide image in paperclip when no image present没有图像时如何在回形针中显示隐藏图像
【发布时间】:2008-11-17 21:13:59
【问题描述】:

如果记录没有关联图像,如何防止调用关联图像的图像标签显示?

<%= image_tag @agent.avatar.url %>

...如果没有与该代理关联的图像,则给我文本“Missing”。我想先测试看看有没有可用的图片,如果测试返回true,再渲染上面的标签。

更好的是,如果没有专门提供图像,我是否可以指定默认图像?

【问题讨论】:

    标签: ruby-on-rails ruby plugins paperclip


    【解决方案1】:

    我使用以下内容来查找模型是否具有关联的附件:

    <% if @agent.avatar.file? %>
      <%= image_tag @agent.avatar.url(:normal) %>
    <% else %>
      No attachment available!
    <% end %>
    

    【讨论】:

    • 甜,用回形针很久了,不知道这个;)
    • 虽然另一个答案是更好的通用解决方案,但我使用这个是因为如果某些内容没有附加图像,我想重新排列布局,而不仅仅是显示占位符图像。
    • 非常好!这是一个简单的快速修复。
    【解决方案2】:

    如果头像有多种尺寸:

    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'
    

    【讨论】:

    • 我对具有附件的多个模型做了一个变体,default_url 为 '/images/:style/missing_modelname.png'
    【解决方案3】:

    好的,所以我得到了它的一部分。

    在模型中指定默认图像

    has_attached_file :avatar, :default_url => '/images/brokers/agents/anonymous_icon.jpg'
    

    【讨论】:

      【解决方案4】:

      少了几个字节:

      <% if @agent.avatar? %>
        <%= image_tag @agent.avatar.url(:normal) %>
      <% else %>
        No attachment available!
      <% end %>
      

      【讨论】:

        【解决方案5】:

        最好使用 :default_url 而不是条件。

        【讨论】:

          【解决方案6】:

          如果在模型中指定了 default_url,你可以使用现有的方法吗?检查 url 是默认的还是上传的。

          <% if @agent.avatar.present? %>
            <%= image_tag @agent.avatar.url(:normal) %>
          <% else %>
            No attachment available!
          <% end %>
          

          【讨论】:

            【解决方案7】:

            你可以用这个

            user.photo.exists?(:medium).
            

            【讨论】:

              【解决方案8】:

              我之前也遇到过同样的问题,但是通过使用解决了它:

              <% if @post.image.exists? %>
              <%= image_tag @post.image.url %>
              <% end %>
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-11-14
                • 1970-01-01
                • 2017-05-04
                • 1970-01-01
                相关资源
                最近更新 更多