views:

81

answers:

2

Hi, I have the following two models

class ContactField < ActiveRecord::Base
end

class Address < ContactField
end

class Phone < ContactField
end

and

class Contact < ActiveRecord::Base
end

class Company < Contact
end

class Person < Contact
end

I want one contact, no matter is it Company or Person, to have many ContactFields(Addresses and Phones)... So where should I put those has many and belongs to? Thanks

A: 

You already said it in plain english :-)

I want one contact, no matter is it Company or Person, to have many ContactFields(Addresses and Phones)... So where should I put those has many and belongs to? Thanks


class Contact < ActiveRecord::Base
 has_many :contact_fields
end

class ContactField < ActiveRecord::Base
 belongs_to :contact
end

This Relationship will be inherited by both address and phone

Rishav Rastogi
+1  A: 

Looks like you're describing a belongs to relationship. The associations should be defined in the parent class, so they can be inherited by the subclasses.

class ContactField < ActiveRecord::Base
  belongs_to :contact
  belongs_to :company, :foreign_key => :contact_id
  belongs_to :person, :foreign_key => :contact_id
end

class Contact < ActiveRecord::Base
  has_many :contact_fields
  has_many :addresses
  has_many :phones
end

However @contact.contact_fields will just return ContactField records. If you need the methods defined in any of the sub classes you can always use the becomes method. There are a few ways around that. Such adding the extra associations, like I did. Or using ActiveRecord::Base#becomes

EmFi