On 3/2/06, dblack / wobblini.net <dblack / wobblini.net> wrote:
> Hi --
>
> On Fri, 3 Mar 2006, Charlie Bowman wrote:
>
> > The only time this nil problem occurs for me is with rails views.  With
> > all other ruby (about half my time is spent in ruby and the other half
> > web apps) code, I never have the nil problem unless I've written bad
> > code.  I feel like web templates should not throw errors if you pass nil
> > values.
>
> Probably the best thing is to do whatever's necessary in the
> controller to make sure the template can coast.  So you could, for
> example, put list.items (or whatever) in @items, making sure in
> advance that it's an empty array if there aren't any.
>
>
> David

Just to illustrate a point about Rails, I had a similar problem. Some
other code allowed a record to be posted to the DB w/o a good
referential link. IOW, the FK in the record pointed to a missing
record in the linked to table. The Rails view just spit out an
attribute of the linked table and that caused the app to crash because
table1.table2 was nill and table1.table2.field => 'field' was not a
valid method of nil.

So I tried the trick posted earlier and it cleaned it up nicely. I'm
sure that this problem comes up all the time, and there are probably
better ways to handle it, but this abstraction was quite nice:

In the controller's helper, I added a method_missing dispatcher:

module MycontrollerHelper
 def method_missing(methodname, *args)
   "MISSING RECORD"
 end
end

In the view: (in my case rxml)

   xml << (table1.table2 || self).field

Hopefully, you have no other need for method_missing in your view.

I'd be interested in others take on this common problem.

Ed