0

我见过一些文章处理这个问题,并试图确定最佳解决方案。多态has_one关联和Rails 3的多重继承

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

所以理论上我觉得想多态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支持多态。那么,是否有一种干净的Ruby方式来实现我的目标?我觉得这是在那里几乎...

回答

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 
+0

啊哈!我会试试这个,我被困在一个客户“属于”调查与其他方式的语义上,但我现在看到这把外键放在我想要的地方。我将把我的基类变成一个模块,并报告回去...... – user206481

+0

@ user206481它是怎么回事? –