# Polymorphic -\> polymorphic relations

**URL:** <https://www.ruby-forum.com/t/polymorphic-polymorphic-relations/166985>\
**Category:** Rails\
**Created:** [May 1, 2009, 6:51pm UTC](https://www.ruby-forum.com/t/polymorphic-polymorphic-relations/166985 "2009-05-01T18:51:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [May 1, 2009, 6:51pm UTC](https://www.ruby-forum.com/t/polymorphic-polymorphic-relations/166985/1 "2009-05-01T18:51:56Z")

</div>

I have 2 polymorphic models that I am trying to relate to each other:

class Company \< ActiveRecord::Base  
belongs\_to :business, :polymorphic =\> true  
has\_many :people  
has\_and\_belongs\_to\_many :mops  
end

class Person \< ActiveRecord::Base  
belongs\_to :contactable, :polymorphic =\> true  
belongs\_to :company  
end

class Contractorcompany \< ActiveRecord::Base  
has\_one :company, :as =\> :business, :dependent  
=\> :destroy, :foreign\_key =\> :business\_id  
end

class Contactcompany \< ActiveRecord::Base  
has\_one :company, :as =\> :business, :dependent  
=\> :destroy, :foreign\_key =\> :business\_id  
end

The problem is that when I select a person according to  
contactable\_type and then pull the company name I get hte company in  
the wrong table. Is there a way to make it so I do this:

@contractor = Contractor.find(params[:contractorid])  
@company=Person.find\_by\_contactable\_id\_and\_contactable\_type  
(@contractor.id,‘Contractor’).company.business.name

It will pull from the contractorcompany table and not the  
contactcompany table?

---

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [May 2, 2009, 1:47am UTC](https://www.ruby-forum.com/t/polymorphic-polymorphic-relations/166985/2 "2009-05-02T01:47:56Z")

</div>

Try This:

class Company \< ActiveRecord::Base  
belongs\_to :business, :polymorphic =\> true  
has\_many :people  
has\_and\_belongs\_to\_many :mops  
end

class Person \< ActiveRecord::Base  
belongs\_to :contactable, :polymorphic =\> true  
belongs\_to :company  
end

class Contractorcompany \< Company

end

class Contactcompany \< Company

end

USE Inheritance… Not sure if I got the syntax correct but I think you  
get  
the idea…

* * *

Steve Shepherd  
Mob:+64 (0) 27 4338154  
Email: removed\_email\_address@domain.invalid  
Analyst
