2014-10-24 3 views
3

그래서 나는이 모델이 :레일 : Belongs_to 다형성 협회 + 조건

class Model < ActiveRecord::Base 
    attr_accessible :to_id, :to_type 

    belongs_to :to, polymorphic: true 

end 

belongs_to가 특정 유형에있을 때 나는 또 다른 관계를 추가 할 수 있는지 궁금 :

class Model < ActiveRecord::Base 
    attr_accessible :to_id, :to_type 

    belongs_to :to, polymorphic: true 
    belongs_to :to_user, :foreign_key => :to_id, :conditions => ['to_type = ?', 'User'] # doesn't work 
    # OR MAYBE 
    belongs_to :to_user, :foreign_key => :to_id, :foreign_class => 'User' # It doesn't check on Model's to_type... 
end 

그래서 my_model.to_user을 그 존재하는 경우 user을 반환하고 설정되지 않았거나 다른 클래스 인 경우 nil을 반환합니다.

레일 사용하기 3.2

감사합니다!

답변

2

당신은

belongs_to :to_user,-> {where(:to_type=> 'User')}, :foreign_key => :to_id 

양식처럼 그 내부 상태가 더 그러한 경우이 association callbacks

0

에 봐 곳에 사용하고, 나는 당신의 질문을 이해 가정 할 수 있습니다, 난 아마 별도의 방법을 추가 명확성을 위해.

def to_user 
    #user-exclusive association retrieval 
    type = self.to_type == 'User' 
    User.find(self.to_id) if type 
end