Skip to content

关于图片栏在资料库中为nil值判断问题 #91

@liangchaob

Description

@liangchaob

在商城项目中,需要显示资料库图片栏是否有值(是否上传了图片),如果没的话就把它设置成默认的nopic图片,在view中:

        <!-- 显示图判断 -->
        <% if no_pic?(@product) %>
          <img src="/nopic.png" alt="no picture" class="img-responsive">
        <% else %>
          <img src="<%= @product.image %>" alt="<%= @product.title %>" class="img-responsive">
        <% end %>

这里面的no_pic放在了helper中

    def no_pic?(product)
        product.image.length == 0
    end

这样判断是否有图确实是有效的,但是以为正常的helper写法是判断是否空值,也就是:

    def no_pic?(product)
        product.image == nil
    end

然而这样判断发现是无效的,换回length==0后,使用pry插入了一个探针,发现

[4] pry(#<#<Class:0x007faac1891c50>>)> @product.image
=> #<ImageUploader:0x007faabf4365e0
 @model=
  #<Product:0x007faabf514020
   id: 7,
   title: "尸体 no.7",
   description: "这个使用seed创建的第 7 具尸体",
   quantity: 5,
   price: 51,
   created_at: Wed, 26 Oct 2016 07:43:43 UTC +00:00,
   updated_at: Wed, 26 Oct 2016 07:43:43 UTC +00:00,
   image: nil>,
 @mounted_as=:image>

这个字段居然不是一个string,那除了这种length==0,有没有更正规的方法判断呢。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions