Views/Controllers for polymorphic association

Hello,
I’m wondering what a good way is to create forms for polymorphic
associations (or what syntax I can use). A simple example should
suffice.

For example, I’ve got models that look like:

Tournament —> belongs_to :place, :polymorphic => true
Country --> has_many :tournaments, :as=> :place
Continent --> has_many :tournaments, :as=> :place

I’m more concerned about the belongs_to part of the association, ie what
the form code for Tournament should look like. I want the UI to have a
select list, where the user can choose a country or a continent (can be
in the same list or separate lists, doesn’t matter). Then the
controller should be able to create/update the tournament by setting
place correctly.

Thanks!

Osman,

I’ve just been revisiting this issue for a project. I’m a relative
noob so my approach may not be the “correct” one. I’ve created a
plugin called acts_as_polymorph that:

Proxies the attributes from the polymorph table into the attribute
table
Overwrites the new, save and update methods to synchronise updates to
both tables in a transaction
Implements find_poly_* methods via method_missing that scopes the
finds and :includes the polymorph table

With this approach you can:

  1. Treat all attributes of the polymorph table as if they are part of
    the attribute table(s)
  2. Do normal new, create, save, updates and ensure tables are
    synchronised
  3. Have extended finders that include the polymorph table
    automatically

For forms, this means you just treat the attributes from the polymorph
table as if
they are in the attribute table - no special handling requried.

My code isn’t finished (no tests, not implemented destroy, …) but
its working well enough to suggest this might be a reasonable
strategy. Happy to share the code
as-is if you want, just email me.

Cheers --Kip

On Nov 6, 9:22 am, Osman O. [email protected]