ActsAsProxy

Posted by Lance Ivy Thu, 05 Jul 2007 22:50:00 GMT

At RailsConf07 someone asked me how to simplify forms in ActiveScaffold. What they wanted was to blend attributes from an associated model in with the main model. The premise was that the user doesn’t need to know about the separate models, so why differentiate them on the form? Well we talked and came up with a solution where you proxy methods from one model to another, then add those methods to ActiveScaffold as virtual attributes.

People are still asking about this. I figure it’s time to abstract the behavior, right? Introducing ActsAsProxy, a very simple plugin that lets you do something like:

1
2
3
4
5
6
7
8
9
10
11
class User < ActiveRecord::Base
  has_one :address
  proxies :address, :city, :state, :zip
end

u = User.new
u.address_city = 'Schenectady'
u.address_state = 'New York'
u.address_zip = 12345

assert_equal u.address_city, u.address.city

Posted in , ,  | Tags  | 2 comments

Comments

  1. linoj said 5 months later:

    hi, could you explain the difference between this, delegate (http://caboo.se/doc/classes/Module.html#M003130), and the ar-delegation plugin (http://daveverwer.com/2007/3/16/activerecord-delegation) ?

  2. Lance said 5 months later:

    Sure.

    The simple delegate method provided in ActiveSupport only does one thing: forward a method to another object. It doesn’t even check that the other object exists before forwarding.

    It looks like AR-Delegation improves on the situation by checking for nil conditions as well as providing lots of semantic sugar so you can specify a whole bunch of fields at once.

    Neither the delegate method nor the AR-Delegation plugin create attribute writers, though. And that’s actually where ActsAsProxy shines – it creates both the attribute reader and the attribute writer, and it creates an attribute writer that handles the nil condition by creating and saving a new associated object.

    So, in summary: the delegate method is incredibly simplistic, and the AR-Delegation method doesn’t bother with writer methods.

(leave url/email »)

   Comment Markup Help Preview comment