Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %>
like image 362
Satish Avatar asked Jul 07 '11 18:07

Satish


People also ask

How do you check if a variable is nil in Ruby?

That's the easy part. In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

What is ||= in Ruby?

a ||= b is a conditional assignment operator. It means: if a is undefined or falsey, then evaluate b and set a to the result. Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.

Is nil a Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement. Now: There is ONLY one nil object, with an object_id of 4 (or 8 in 64-bit Ruby), this is part of why nil is special.

How declare variable in Rails?

@title is an instance variable - and is available to all methods within the class. In Ruby on Rails - declaring your variables in your controller as instance variables ( @title ) makes them available to your view.


1 Answers

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.

like image 84
jergason Avatar answered Sep 21 '22 10:09

jergason