Satish
Satish

Reputation: 6485

Ruby on Rails: Using default value, when the variable is null or empty

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 %>

Upvotes: 14

Views: 18370

Answers (2)

Jamison Dance
Jamison Dance

Reputation: 20184

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"
  end
end

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.

Upvotes: 21

ronnieonrails
ronnieonrails

Reputation: 2199

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.

Upvotes: 1

Related Questions