Forum: Ruby on Rails Handling nil attributes in views

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D4e51fd9554030ab55c379fdc1a34826?d=identicon&s=25 Keith Lancaster (klancaster)
on 2006-02-19 16:43
The problem at hand is how to handle missing (but not required) refs to
other objects when working in a view (that was not clear - gimme a
minute:-). There has been some discussion of this on the wiki, but I was
wondering what others thought about handling this.

I have class A that belongs_to class B, and I want to display an
attribute of B in the view, so I do something like the following:

<%= A.B.b_attr || "Value not available" %>

B is an optional attribute, i.e., it is not required to be set, so this
throws an exception under those circumstances.

Option 1:

<%= A.B.b_attr rescue "Value not available" %>

Option 2:

Define the reader for B_attr

alias old_b_attr b_attr
def b_attr
  if self.b_attr_id.nil?
    B.new   # essentially, create a new empty version
  else
    old_b_attr
  end
end

BTW, I'm using the alias method because read_attribute does not work
(afaik) with fkey relationships.

Both of these methods  work, but still don't quite feel "right". Any
suggestions?

TIA,
Keith
This topic is locked and can not be replied to.