2010-05-14 60 views
0

我使用的代碼:顯示消息,如果沒有照片呈現

<%= image_tag site.photo.url(:small) if site.photo.file? %> 

告訴我的應用程序,如果沒有與特定職位(網站在這種情況下)相關的照片,以顯示任何內容。有沒有辦法根據這個來渲染一條消息。例如「沒有帖子的圖像」。我只是試着做

<%= if site.photo.file? %> 
    <p> no image with this site </p> 
<% end %> 

但這似乎並不奏效。如果你無法辨別,那麼只能使用紅寶石和導軌。

+0

我不熟悉的軌道,但不會如site.photo.file?如果有照片返回true?你不想要與此相反嗎? – Beanish 2010-05-14 14:58:17

+0

是的,你是正確的,我認爲通過.empty解決?或.blank?除了最後,但我認爲有一種方法可以在第一組代碼中使用和'else'語句,但不確定這裏的語法。 – bgadoci 2010-05-14 15:03:41

回答

1
<%= image_tag(site.photo.url(:small)) rescue "<p>No image</p>" %> 
+0

我以爲你只能與Begin結合使用救援,這是如何工作的? – Schneems 2010-05-14 19:04:07

+0

這是一個「內聯救援」。如果表達式的左側觸發錯誤,則可以使用右側的語句立即恢復它。例如,在上面的例子中,如果'site'沒有'photo','site.photo.url'會抱怨'nil'的未定義方法'url'。而不是做這個測試,只是拯救和渲染「哇!沒有照片,男人。」 – 2010-05-15 19:13:00

2

一個真正簡單的方法是創建一個小的小幫手:

def show_photo_if_exists(photo) 
    photo.file? ? image_tag photo.url(:small) : "No image with this site" 
end 

然後在您查看呼叫:

<%= show_photo_if_exists(site.photo) %> 
+0

如果'site.photo'爲零,則將nil傳遞給'show_photo_if_exists'方法。該方法的第一條語句變成'nil.file?',它會返回一個'undefined method \'文件?'爲零:NilClass'。 – 2010-05-15 19:21:19

+0

它看起來像我使用回形針,在這種情況下,只要網站模型'has_attached_file:photo'然後'site.photo'永遠不會是零,即使它沒有附件。 – aaronrussell 2010-05-15 23:38:19

1

你在正確的軌道上,但失蹤只有在site.photo.file時才顯示一點邏輯?返回false,所以你需要在視圖中使用:(!?注意一鼓作氣site.photo.file前將反轉邏輯)

<%= if !site.photo.file? %> 
    <p> no image with this site </p> 
<% end %> 

+0

一個簡單的感嘆號,它應該工作! – jigfox 2010-05-14 19:43:34

+0

這不是慣用的ruby。 Ruby除非有一個「if not」關鍵字。 '%除非site.photo.file? %> ... **注意:**,你想'<%...',而不是'<%= ...'。 – 2010-05-15 19:14:55

4

您的代碼將輸出有照片時有no image with this site。使用這個來代替:

<% unless site.photo.file? %> 
    <p> no image with this site </p> 
<% end %> 

甚至更​​好:

<% if site.photo.file? %> 
    <%= image_tag site.photo.url(:small) %> 
<% else %> 
    <p> no image with this site </p> 
<% end %> 
+0

'<%= ... %>'輸出到文檔。寫顯示邏輯(例如)'<%除非site.photo.file? %> ...'(沒有'='字符) – 2010-05-15 19:17:34

+0

感謝您提供此信息,現在已更正 – jigfox 2010-05-16 16:03:28