开发者

Relation between two single-table inheritance models

开发者 https://www.devze.com 2022-12-13 21:51 出处:网络
I have the following two models class ContactField < ActiveRecord::Base end class Address < ContactField

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

精彩评论

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

关注公众号