Forum: Ruby on Rails how to prevent image_tag helper throwing exception if the ur

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kris L. (Guest)
on 2005-11-25 17:55
(Received via mailing list)
If I store the path/filename of an image in the database how do I
prevent "image_tag" helper from throwing an exception if a filename/path
has not been set?

<%= image_tag @product.image %>
or
<%= image_tag url_for_file_column("product", "image") %>

Many thanks, K.
dez (Guest)
on 2005-11-25 19:32
(Received via mailing list)
Does this work?

<%= image_tag(@product.image) if @product.image %>
ezra (Guest)
on 2005-11-26 19:10
(Received via mailing list)
On Nov 25, 2005, at 7:51 AM, Kris L. wrote:

> If I store the path/filename of an image in the database how do I
> prevent "image_tag" helper from throwing an exception if a filename/
> path has not been set?
>
> <%= image_tag @product.image %>
> or
> <%= image_tag url_for_file_column("product", "image") %>
>
> Many thanks, K.

Kris-

	You can use this:
> <%= image_tag @product.image rescue nil %>

> <%= image_tag url_for_file_column("product", "image")  rescue nil %>


Cheers-
-Ezra Z.
WebMaster
Yakima Herald-Republic Newspaper
removed_email_address@domain.invalid
509-577-7732
christopher.k.hall (Guest)
on 2005-11-26 19:35
(Received via mailing list)
i might do something like so...

<%= image_tag product.get_image, :border => 0 %>

class Product < ActiveRecord:Base
  ...
  # returns either the image (path/name stored in db)
  # or default image name if image is nil (null in db)
  def get_image
    # default_product_image.jpg in public/images directory
    (image.nil?) ? "default_product_image.jpg" : image
  end
end
This topic is locked and can not be replied to.