Ruby on rails 3 多态性与Rails 3有一个关联和多个继承

Ruby on rails 3 多态性与Rails 3有一个关联和多个继承,ruby-on-rails-3,inheritance,polymorphic-associations,has-one,Ruby On Rails 3,Inheritance,Polymorphic Associations,Has One,我看过一些关于这个问题的帖子,我正在努力确定最佳解决方案 从语义上讲,我想要一个与调查有一对一关系的客户机模型。有不同类型的调查,有不同的领域,但我想在他们之间分享大量的代码。由于不同的字段,我希望调查使用不同的数据库表。不需要搜索不同类型的调查。感觉上,我希望在客户机表中使用外键,以便快速检索和潜在地快速加载调查 所以理论上我想多态性有一个和多个继承,比如: class Client < ActiveRecord::Base has_one :survey, :polymorphic

我看过一些关于这个问题的帖子,我正在努力确定最佳解决方案

从语义上讲,我想要一个与调查有一对一关系的客户机模型。有不同类型的调查,有不同的领域,但我想在他们之间分享大量的代码。由于不同的字段,我希望调查使用不同的数据库表。不需要搜索不同类型的调查。感觉上,我希望在客户机表中使用外键,以便快速检索和潜在地快速加载调查

所以理论上我想多态性有一个和多个继承,比如:

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
class客户端true
结束
班级调查
#共享代码的基类,与db表不对应
def实用程序法
结束
结束
类Type1Survey:调查
结束
类Type2Survey:调查
结束
#在type1_surveys表中创建新条目,在client表中设置survey_id
@client.survey=Type1Survey.create()
@client.survey.nil?#客户填写调查了吗?
@client.survey.utility#u方法#基本类调查的访问方法
@client.survey.type1field#访问Type1Survey特有的字段
@client2.survey=Type2Survey.create()
@client2.survey.type2field#访问Type2Survey特有的字段
@客户2.调查.效用法

现在,我知道Ruby不支持多重继承,也不支持:多态。那么,有没有一种干净的Ruby方法来实现我的目标呢?我觉得它几乎就在那里…

我会这样做:

class Client < ActiveRecord::Base
  belongs_to :survey, :polymorphic => true
end

module Survey
  def self.included(base)
    base.has_one :client, :as => :survey
  end

  def utility_method
     self.do_some_stuff
  end
end

Type1Survey < ActiveRecord::Base
  include Survey

  def method_only_applicable_to_this_type
    # do stuff
  end
end

Type2Survey < ActiveRecord::Base
  include Survey
end
class客户端true
结束
模块调查
def自带(基本)
base.has_one:client,:as=>:survey
结束
def实用程序法
赛尔夫,做点什么
结束
结束
Type1Survey
Aha!我会试试这个,我一直停留在“属于”调查的客户机的语义上,而不是相反,但是我现在看到这把外键放到了我想要的地方。我将把我的基类也变成一个模块,并向您报告…@user206481它进行得如何?