我看过一些处理这个问题的帖子,并试图确定最佳解决方案。
从语义上讲,我想要一个与调查具有一对一关系的客户模型。有不同类型的调查具有不同的领域,但我想在它们之间共享大量代码。由于不同的字段,我想要用于调查的不同数据库表。无需搜索不同类型的调查。感觉就像我想要 Client 表中的外键用于快速检索和潜在的调查加载。
所以理论上我想我想要多态的 has_one 和多重继承是这样的:
class Client < ActiveRecord::Base
has_one :survey, :polymorphic => true
end
class Survey
# base class of shared code, does not correspond to a db table
def utility_method
end
end
class Type1Survey < ActiveRecord::Base, Survey
belongs_to :client, :as => :survey
end
class Type2Survey < ActiveRecord::Base, Survey
belongs_to :client, :as => :survey
end
# create new entry in type1_surveys table, set survey_id in client table
@client.survey = Type1Survey.create()
@client.survey.nil? # did client fill out a survey?
@client.survey.utility_method # access method of base class Survey
@client.survey.type1field # access a field unique to Type1Survey
@client2.survey = Type2Survey.create()
@client2.survey.type2field # access a field unique to Type2Survey
@client2.survey.utility_method
现在,我知道 Ruby 不支持多重继承, :has_one 也不支持 :polymorphic。那么有没有一种干净的 Ruby 方法来实现我的目标?我觉得它几乎就在那里...