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方式來實現我的目標?我覺得這是在那裏幾乎...
啊哈!我會試試這個,我被困在一個客戶「屬於」調查與其他方式的語義上,但我現在看到這把外鍵放在我想要的地方。我將把我的基類變成一個模塊,並報告回去...... – user206481
@ user206481它是怎麼回事? –