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它是怎麼回事? –