I couldn’t find a complete example of a double polymorphic
relationship so I will post what I have in case someone comes across
this using Google. It seems to be working so far, but I don’t know if
I have everything setup correctly yet.
install as a plugin or as a gem
git submodule add git://github.com/fauna/has_many_polymorphs.git
vendor/plugins/has_many_polymorphs
git submodule init
git submodule update
setup the models
ruby script/generate model User name:string
ruby script/generate model Business name:string
ruby script/generate model Charity name:string
ruby script/generate model Address street:string street2:string
city:string state:string zip:string
ruby script/generate model EmailAddress address:string
ruby script/generate model Website address:string
ruby script/generate model PhoneNumber number:string
ruby script/generate model Linkage
edit the linkage migration
class CreateLinkages < ActiveRecord::Migration
def self.up
create_table :linkages do |t|
t.references :origin, :polymorphic => true
t.references :destin, :polymorphic => true
t.timestamps
end
end
def self.down
drop_table :linkages
end
end
add the relationships to the models
Origins
class User < ActiveRecord::Base
has_many_polymorphs :destins, :from =>
[:addresses, :email_addresses, :phone_numbers, :websites], :through
=> :linkages
end
class Business < ActiveRecord::Base
has_many_polymorphs :destins, :from =>
[:addresses, :email_addresses, :phone_numbers, :websites], :through
=> :linkages
end
class Charity < ActiveRecord::Base
has_many_polymorphs :destins, :from =>
[:addresses, :email_addresses, :phone_numbers, :websites], :through
=> :linkages
end
Double Polymorphic Join Model
class Linkage < ActiveRecord::Base
# id:int
# origin_id:int
# origin_type:string
# destin_id:int
# destin_type:string
belongs_to :origin, :polymorphic => true
belongs_to :destin, :polymorphic => true
acts_as_double_polymorphic_join(
:origins => [:users, :businesses, :charities],
:destins =>
[:addresses, :email_addresses, :phone_numbers, :websites]
)
end
Destins
class Address < ActiveRecord::Base
has_many_polymorphs :origins, :from =>
[:users, :businesses, :charities], :through => :linkages
end
class EmailAddress < ActiveRecord::Base
has_many_polymorphs :origins, :from =>
[:users, :businesses, :charities], :through => :linkages
end
class PhoneNumber < ActiveRecord::Base
has_many_polymorphs :origins, :from =>
[:users, :businesses, :charities], :through => :linkages
end
How It Works
rake db:migrate
ruby script/console
u=User.new
u.name=“Scott”
u.save
w=Website.new
w.address=“http://google.com”
w.save
u.destins << w
u.destins
=> [#<Website id: 1, address: “http://google.com”, created_at:
“2009-01-08 21:55:12”, updated_at: “2009-01-08 21:55:12”>]
w.origins
=> [#<User id: 1, name: “scott”, created_at: “2009-01-08 21:54:00”,
updated_at: “2009-01-08 21:54:00”>]
u.websites
=> [#<Website id: 1, address: “http://google.com”, created_at:
“2009-01-08 21:55:12”, updated_at: “2009-01-08 21:55:12”>]