How do I handle nils in views?

Posted by Badweather on Stack Overflow See other posts from Stack Overflow or by Badweather
Published on 2010-04-08T15:09:44Z Indexed on 2010/04/08 15:13 UTC
Read the original article Hit count: 516

Filed under:
|

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!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby