Saw this trick on the ruby-talk list and wanted to share my use of it
in a Rails view.
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:
def method_missing(methodname, *args)
In the view: (in my case rxml)
xml << (table1.table2 || self).field
I think for rhtml it would be :
<%= (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.