Has Many Polymorphs plugin

Plugin details

An ActiveRecord plugin for self-referential and double-sided polymorphic associations.

Repositorysvn://rubyforge.org/var/svn/fauna/has_many_polymorphs/trunk Author Evan Weaver Tags polymorphic, association LicenseUnknown

Documentation

Install the plugin:
ruby script/plugin install svn://rubyforge.org/var/svn/fauna/has_many_polymorphs/trunk

Configuration
===============

Setup the parent model as so:

  class Kennel < ActiveRecord::Base
    has_many_polymorphs :guests, :from => [:dogs, :cats, :birds]
  end


The join model:

  class GuestsKennel < ActiveRecord::Base
    belongs_to :kennel
    belongs_to :guest, :polymorphic => true
  end


One of the child models:

  class Dog < ActiveRecord::Base
    # nothing
  end


See ActiveRecord::Associations::PolymorphicClassMethods for more configuration options.

Helper methods example
======================

  >> k = Kennel.find(1)
  #
  >> k.guests.map(&:class) 
  [Dog, Cat, Cat, Bird]
  
  >> k.guests.push(Cat.create); k.cats.size
  3
  >> k.guests << Cat.create; k.cats.size
  4
  >> k.guests.size
  6

  >> d = k.dogs.first
  #
  >> d.kennels 
  [#]
  
  >> k.guests.delete(d); k.dogs.size
  0
  >> k.guests.size
  5  


Note that the parent method is always plural, even if there is only one parent (Dog#kennels, not Dog#kennel).

See ActiveRecord::Associations::PolymorphicAssociation for more helper method details.

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | (0 older versions) | Last edited by: hardway, 7 months ago