Take the 2-minute tour ×

I have this code-snippet in html erb.

For some objects the cover_image_url is empty, how do i modify this code block to use a default value ,when that property is null or empty?

<%@books.each do |book|%>
        $('#bookContainer').append('<div class="conn"><p><img class="floatright" src="<%= h book.cover_image_url%>"><h3><%= h book.title%></h3><h3><%= h book.author%></h3></p></div>');
    <% end %>
share|improve this question
add comment

2 Answers

up vote 12 down vote accepted

You could define a cover_image_url method on your book model that will return a default value if there is nothing set in the database (I am assuming that cover_image_url is a column in the book table). Something like this:

class Book < ActiveRecord::Base
  def cover_image_url
    read_attribute(:cover_image_url).presence || "/my_default_link"

This will return "/my_default_link" if the attribute is not set, or the value of the attribute if it is set. See section 5.3 on The Rails 3 Way for more info on this stuff. Defining a default value for a model in the model layer may be a little cleaner than doing it in the view layer.

share|improve this answer
If you want to treat blanks as nulls for this purpose, you may want to change it to read_attribute(:cover_image_url).presence || "/my_default_link". presence returns the object if it isn't blank, otherwise returns nil. –  Jacob Mattison Jul 7 '11 at 19:55
Thanks, I'll update it. –  Jergason Jul 7 '11 at 20:41
add comment

You can use a local variable inside the loop :

<% url = book.cover_image_url or "/my_default_link" %>

This will take a default link if the first value is nil.

To check both null or empty :

<% url = ((book.cover_image_url.nil? or (book.cover_image_url and book.cover_image_url.empty?)) ? "/my_default_link" : book.cover_image_url) %>

Put the whole thing in a helper to make it cleaner.

share|improve this answer
add comment

Your Answer


