2013-10-08 3 views
2

ActiveRecord 모델이 다른 모델의 대리인 역할을 할 수 있도록 믹스 인을 만들려고합니다. 그래서, 그것을 일반적인 방법을 수행 :ActiveRecord에서 belongs_to 연관을 동적으로 설정하는 방법은 무엇입니까?

class Apple < ActiveRecord::Base 
    def foo_species 
     "Red delicious" 
    end  
end 


class AppleWrapper < ActiveRecord::Base 
    belongs_to :apple 
    # some meta delegation code here so that AppleWrapper 
    # has all the same interface as Apple 
end 


a = Apple.create 
w = AppleWrapper.create 
w.apple = a 
w.foo_species 
# => 'Red delicious' 

I는 믹스 인으로 추상적이 동작하는 것입니다 원하는거야, 내가, 또한 ActiveRecords 클래스를 "래퍼"를 만들 수있는 데이터 모델의 무리 주어진하지만 그렇게 각 래퍼는 특정 클래스에 해당합니다. 왜? 각각의 데이터 모델은 계산, 다른 모델과의 집계를 가지고 있으며 "Wrapper"클래스가 이러한 계산에 해당하는 필드를 포함하기를 원합니다. 래퍼는 동일한 인터페이스를 사용하여 원래 데이터 모델의 캐시 된 버전으로 작동합니다.

각 래퍼를 써야합니다 ... Apple, Orange, Pear에는 각 래퍼 모델이 있습니다.

module WrapperMixin 
    extend ActiveSupport::Concern 
    module ClassMethods 
     def set_wrapped_class(klass) 
     # this sets the relation to another data model and does the meta delegation 
     end 
    end 
end 


class AppleWrapper < ActiveRecord::Base 
    include WrapperMixin 
    set_wrapped_class Apple 
end 

class OrangeWrapper < ActiveRecord::Base 
    include WrapperMixin 
    set_wrapped_class Orange 
end 

나는이 설정 얼마나 : 무슨 래퍼 포인트를 설정하는 클래스 수준의 방법, 라 거기 있도록하지만, 난 그냥 ... 래퍼 행동 밖으로 추상적 인 원하십니까? 그리고 이것은 STI 유형 관계 여야합니까? 즉, 래퍼 클래스에는 wrapped_record_id와 wrapped_record_type이 있어야합니까?

답변

2

set_wrapped_class 메서드에서 belongs_to을 사용할 수 있습니다.

def set_wrapped_class(klass) 
    belongs_to klass.to_s.downcase.to_sym 
end 
관련 문제