Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 两种单表继承模型之间的关系_Ruby On Rails_Has Many_Single Table Inheritance_Belongs To - Fatal编程技术网

Ruby on rails 两种单表继承模型之间的关系

Ruby on rails 两种单表继承模型之间的关系,ruby-on-rails,has-many,single-table-inheritance,belongs-to,Ruby On Rails,Has Many,Single Table Inheritance,Belongs To,我有以下两种型号 class ContactField < ActiveRecord::Base end class Address < ContactField end class Phone < ContactField end class ContactField

我有以下两种型号

class ContactField < ActiveRecord::Base
end

class Address < ContactField
end

class Phone < ContactField
end
class ContactField

class联系人
我想要一个联系人,无论是公司还是个人,都有许多联系人字段(地址和电话)。。。那么我应该把那些有很多属于的放在哪里呢?
谢谢

你已经用简单的英语说了:-)

我想要一个联系人,无论是公司还是个人,都有许多联系人字段(地址和电话)。。。那么我应该把那些有很多并且属于我的东西放在哪里呢?谢谢

类联系人此关系将由地址和电话继承

看起来您正在描述一种归属关系。关联应该在父类中定义,这样子类就可以继承它们

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
class ContactField:联系人\u id
属于:个人,:外键=>:联系人id
结束
类联系人
但是@contact.contact\u字段将只返回ContactField记录。如果需要在任何子类中定义的方法,可以始终使用beans方法。有几种方法可以解决这个问题。像我一样,添加额外的关联。或使用

class Contact < ActiveRecord::Base has_many :contact_fields end class ContactField < ActiveRecord::Base belongs_to :contact end
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