如何检查模特是否有 Carrierwave 的照片?

mar*_*ion 3 ruby-on-rails carrierwave ruby-on-rails-4

我有一个模型——Post可以将图像和文件上传到它们。Carrierwave 中有两个不同的上传器。

我想要做的是,简单检查对象上是否存在上传的照片,如果检测到,我将显示图像标签。但如果不是,那么它什么也不显示。

我试过这个:

<% if post.photo %>
    <%= image_tag post.photo, size: "52", :class => 'entry-avatar' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

但这不起作用,它总是显示:

<img class="entry-avatar" height="52" src width="52">
Run Code Online (Sandbox Code Playgroud)

当它不为空时,它会将文件路径正确地添加到src属性中。

如果我尝试检查photo.nil?它不起作用,即使它看起来应该:

 > a 
 => #<Post id: 1, title: "Fire at Bible College in Christian", photo: nil, body: "A massive fire is now raging at the Bible College ...", created_at: "2014-08-28 08:06:19", updated_at: "2014-09-18 23:35:04", user_id: 1, ancestry: nil, file: nil, status: nil, slug: "fire-at-bible-college-in-christian", publication_status: 1, has_eyewitness: true> 
Run Code Online (Sandbox Code Playgroud)

请注意,当我执行此操作时,:photo上面的属性设置为nil...yet:

 > a.photo
 => #<PhotoUploader:0x00000102e19878 @model=#<Post id: 1, title: "Fire at Bible College in Christian", photo: nil, body: "A massive fire is now raging at the Bible College ...", created_at: "2014-08-28 08:06:19", updated_at: "2014-09-18 23:35:04", user_id: 1, ancestry: nil, file: nil, status: nil, slug: "fire-at-bible-college-in-christian", publication_status: 1, has_eyewitness: true>, @mounted_as=:photo> 
 > a.photo.nil?
 => false 
Run Code Online (Sandbox Code Playgroud)

它不起作用。

是否有 Carrierwave 方法可用于执行此操作或其他方式?

anu*_*sha 5

无需photo使用nil?方法检查属性。您可以a.photo?根据文件是否存在直接检查它是否返回布尔值。