Multiple object forms, delegation, and has_one…
June 3rd, 2008 byI had an ah ha moment that maybe shouldn’t have been such an ah ha moment but it was so I figured I would share it. Yeah so I am sure most of us have had a situation where we needed to have multiple model forms. Most of the time now days I use attribute_fu to solve this issue but attribute_fu doesn’t work with has_one associations. Today I had a situation where I had two fields that were required for a has_one association object. Long story short it came to me that if we just used the delegate method provided by rails that we could essentially act like the attributes we were setting were on the parent model. This meant we only needed to create one form with multiple fields even though some of those fields were actually on a different model. I then remembered that back when I was working with the guys over at ThoughtWorks that we used a Ruby Extension called Forwardable to be able to delegate multiple attributes on one object.
So instead of this:
delegate :first_name, :to => :profile
delegate :last_name, :to => :profile
delegate :some_other_attribute, :to => :profile
side note: I’m not sure but I don’t believe delegate can take multiple attributes (I tried to look this up but for some reason couldn’t find the documentation for this method and didn’t have time to dig in the code)
You could do the following:
include the Ruby Extension Forwardable in the parent model class
include Forwardable
and then add this line:
def_delegators :profile, :first_name, :last_name, :some_other_attribute
So yeah that was my little ah ha moment. I am sure there are even better ways than this but this was better than what we were looking at doing to begin with.

