views:

61

answers:

4

I am using the code:

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

to tell my app to display nothing if there is no photo associated with a particular post (site in this case). Is there a way to render a message along w/ this. For instance "no image with the post". I tried simply doing

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

But that doesn't seem to work. New to ruby and rails if you can't tell.

+2  A: 

A real simple way would be to create a small little helper:

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

Then in your view call:

<%= show_photo_if_exists(site.photo) %>
aaronrussell
if `site.photo` is nil, you're passing nil to the `show_photo_if_exists` method. The first statement of that method becomes `nil.file?` of which will return an `undefined method```file?' for nil:NilClass`.
macek
It looks to me like he's using Paperclip, in which case as long as the Site model `has_attached_file :photo` then `site.photo` will never be nil, not even if it has no attachment.
aaronrussell
+1  A: 

Hey Brandon, try this:

<%= image_tag(site.photo.url(:small)) rescue "<p>No image</p>" %>
macek
I thought you could only use rescue in conjunction with Begin, how does this work?
ThinkBohemian
It's an "inline rescue". If the left side of the expression triggers an error, it can be recovered from immediately with the statement on the right. E.g., in the example above, if `site` does not have a `photo`, `site.photo.url` is going to complain "undefined method `url' for `nil'". Rather than doing testing for this, just rescue and render "Whoa! No photo, man."
macek
+1  A: 

You're on the right track, but missing a bit of logic you want to display it only if site.photo.file? returns false, so you would need to use this in your view:

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

(note the bang! in front of site.photo.file? which will invert the logic.)

ThinkBohemian
a simple exclamation mark and it should work!
jigfox
This is not idiomatic ruby. Ruby has a "if not" keyword `unless`. `<% unless site.photo.file? %> ...` **Note:**, you want `<% ...`, not `<%= ...`.
macek
+1  A: 

Your code will output no image with this site when there is a photo. Use this instead:

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

or even better:

<% if site.photo.file? %>
  <%= image_tag site.photo.url(:small) %>
<% else %>
  <p> no image with this site </p>
<% end %>
jigfox
`<%= ... %>` outputs to the Document. Write display logic as (e.g.,) `<% unless site.photo.file? %> ...` (No `=` character)
macek
thanks for this info, it's corrected now
jigfox