Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
liangchaob opened this issue Oct 27, 2016 · 0 comments
Open

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

liangchaob opened this issue Oct 27, 2016 · 0 comments

Comments

@liangchaob
Copy link

在商城项目中,需要显示资料库图片栏是否有值(是否上传了图片),如果没的话就把它设置成默认的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,有没有更正规的方法判断呢。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant