Forum: Ruby on Rails Cleaner code in rails view

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.
822a498b26a2cb7d1f0f2e7e37ce61b2?d=identicon&s=25 Ed Howland (Guest)
on 2006-03-03 00:48
(Received via mailing list)
Hi all.

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:

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

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.

Ed
This topic is locked and can not be replied to.