views:

81

answers:

4

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!

+4  A: 

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

Dustin M.
Using unless with the .blank? method was just what I needed. Thanks for the help!
Badweather
You can also do `<%= @contact.band.name if @contact.band.present? %>`
John Topley
Your welcome badweather! Welcome to Stack Overflow btw and don't forget to accept the answer. (Shameless reputation grubbing) ;) And John is right, you can use an if method with "present?" Cheers!
Dustin M.
Answer accepted. :) Thanks John for that other suggestion as well. I will try both.
Badweather
A: 

<%= @contact.band if @contact.band %> also works

fivetwentysix
A: 
<%= @contact.try(:band).try(:name) %>

This will return nil if band or name do not exist as methods on their respective objects.

Ryan Bigg
+1  A: 

You can use Object#andand for this:

<%= @contact.band.andand.name %>
Christoffer Hammarström