Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle nils in views?

I have the following models set up:

class Contact < ActiveRecord::Base
  belongs_to :band
  belongs_to :mode

  validates_presence_of :call, :mode
  validates_associated :mode, :band
  validates_presence_of :band, :if => :no_freq?
  validates_presence_of :freq, :if => :no_band?

protected

  def no_freq?
    freq.nil?
  end

  def no_band?
    band.nil?
  end
end

class Band < ActiveRecord::Base
  has_many :logs
end

class Mode < ActiveRecord::Base
  has_many :logs
end

When I enter a frequency on my new view it allows for no band to be specified if a freq is entered. This creates a problem in my other views though because band is now nil. How do I allow for band not to be specified and just show up as empty on my index and show views, and then in the edit view allow one to be specified at a later point in time.

I have been able to get my index to display a blank by doing:

contact.band && contact.band.name

But I'm not sure if this is a best approach, and I'm unsure of how to apply a similar solution to my other views.

Many thanks from a rails newb!

like image 670
Badweather Avatar asked Apr 08 '10 15:04

Badweather


2 Answers

In my views, I use the following for potentially nil objects in my views:

<%= @contact.band.name unless @contact.band.blank? %>

if your object is an array or hash, you can use the empty? function instead.

<%= unless @contacts.empty? %>
 ..some code
<% end %>

Hope this helps!

D

like image 190
Dustin M. Avatar answered Nov 11 '22 21:11

Dustin M.


A couple years old but still a top Google result for "rails view handle nil" so I'll add my suggestion for use with Rails 3.2.3 and Ruby 1.9.3p0.

In application_helper.rb, add this:

def blank_to_nbsp(value)
  value.blank? ? "&nbsp;".html_safe : value
end

Then to display a value in a view, write something like this:

<%= blank_to_nbsp contact.band %>

Benefits:

  • "blank" catches both nil values and empty strings (details).
  • Simply omitting a nil object, or using an empty string, may cause formatting issues. &nbsp; pushes a non-breaking space into the web page and preserves formatting.
  • With the "if" and "unless" suggestions in other answers, you have to type each object name twice. By using a helper, you only have to type each object name once.
like image 3
Mark Berry Avatar answered Nov 11 '22 21:11

Mark Berry