如何与另一个模型进行多态模型关联

时间:2014-08-19 09:38:58

标签: ruby-on-rails-4 polymorphic-associations

我有两个基本模型:

class Case < ActiveRecord::Base
 has_many :contacts
end

class Contact < ActiveRecord::Base
 belongs_to :case
 belongs_to :contactable, :polymorphic => true, :foreign_key => :contactable_id
end

我也有很多型号的子类型&#34;联系模式:

class Attorney < ActiveRecord::Base
 has_one :contact, as: :contactable, dependent: :destroy

 accepts_nested_attributes_for :contact
end


class Client < ActiveRecord::Base
 has_one :contact, as: :contactable, dependent: :destroy

 accepts_nested_attributes_for :contact
end

我使用多态关联而不是STI,因为我不希望有一个表存储所有字段,这可能会有点慢和压倒性。

我想知道Case模型中的has_many:contacts行是否正确。我尝试在我的控制台中使用它,但它并没有像我预期的那样工作。我错过了什么吗?

我基本上想要一个关联,其中一个Case可以有很多联系人,一个联系人可以属于很多情况。联系人可以是任何类型(律师或客户或联系人)。我希望它像case has_many一样容易:联系

0 个答案:

没有答案