开发者

Relation between two single-table inheritance models

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开发者_Go百科 Person, to have many ContactFields(Addresses and Phones)... So where should I put those has many and belongs to? Thanks


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜