0

이 문제를 다루는 몇 가지 게시물을 보았으며 가장 좋은 솔루션을 결정하려고합니다.다형성 has_one 연관성과 Rails 3의 다중 상속

의미 상, 설문 조사와 일대일 관계가있는 클라이언트 모델이 필요합니다. 다양한 분야의 설문 조사가 있지만 그 사이에 많은 양의 코드를 공유하고 싶습니다. 다른 필드 때문에 나는 조사를 위해 다른 데이터베이스 테이블을 원한다. 여러 유형의 설문 조사를 검색 할 필요가 없습니다. 설문 조사를 신속하게 검색하고 잠재 고객을로드 할 수 있도록 Client 테이블에 외래 키가 필요합니다.

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 

는 지금, 나는 루비는 다중 상속을 지원하지 않습니다 알고도 수행합니다 : has_one 지원 : 다형성

그래서 이론적으로 나는이 같은 다형성 has_one 및 다중 상속 뭔가를 원하는 생각 . 그래서 내가 얻는 것을 달성 할 수있는 깨끗한 루비 방법이 있습니까? 그것은 바로 거기 거의처럼 나는

답변

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 어떻게 되었습니까? –