Forum: Ruby on Rails polymorphic -> polymorphic relations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris H. (Guest)
on 2009-05-01 20:51
(Received via mailing list)
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?
Steve Shepherd (Guest)
on 2009-05-02 03:47
(Received via mailing list)
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
This topic is locked and can not be replied to.