14

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

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
From this Rubocop Styleguide you can see that the preferred is self[:amount] not read_attribute(:amount)
1

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.

1 Comment

or didn't work for me; this was my solution: url = book.cover_image_url || "/my_default_link"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.