2014-09-25 39 views
2

我有一個模型 - Post - 可以有圖像&上傳到他們的文件。 Carrierwave有兩個不同的上傳器。如何檢查模型是否與Carrierwave有照片?

我想要做的是,做一個簡單的檢查對象的照片上傳的存在,如果檢測到我會顯示圖像標記。但如果不是,那麼它什麼都沒有顯示。

我嘗試這樣做:

<% if post.photo %> 
    <%= image_tag post.photo, size: "52", :class => 'entry-avatar' %> 
<% end %> 

但是,這並不工作,它始終會顯示此:

<img class="entry-avatar" height="52" src width="52"> 

當不爲空,它增加了文件路徑,正確,以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> 

注意,:photo屬性上面設置爲nil ...然而,當我這樣做:

> 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 

它不起作用。

有沒有可以用來做這個或者其他方式的Carrierwave方法?

+1

一旦檢查,看看輸出是什麼:'a.photo?' – anusha 2014-09-26 03:11:25

回答

3

不需要檢查photo屬性與nil?方法。您可以直接檢查像a.photo?它基於文件是否存在返回布爾值。