0

我看过一些处理这个问题的帖子,并试图确定最佳解决方案。

从语义上讲,我想要一个与调查具有一对一关系的客户模型。有不同类型的调查具有不同的领域,但我想在它们之间共享大量代码。由于不同的字段,我想要用于调查的不同数据库表。无需搜索不同类型的调查。感觉就像我想要 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 方法来实现我的目标?我觉得它几乎就在那里...

4

1 回答 1

0

这是我将如何做到这一点:

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
于 2012-10-18T15:22:41.507 回答