2011-09-20 5 views
3

내 응용 프로그램에서 모델이 있습니다has_one : 다형성을 통해 가능합니까?

클래스 코멘트 < 액티브 :: 자료

belongs_to :commentable, :polymorphic => true 

클래스 프로젝트 < 액티브 :: 자료

has_many :discussions, :dependent => :destroy 
has_many :tickets, :dependent => :destroy 

클래스 토론 < 액티브 :: 자료

has_many :comments, :as => :commentable, :dependent => :destroy 

클래스 티켓 < 액티브 :: 자료

has_many :comments, :as => :commentable, :dependent => :destroy 

모든 것이 잘 작동하지만 가끔은하지 매우 convinient이다 commentable, 즉 comment.commentable.project를 통해 주석에서 프로젝트를 가져옵니다. 코멘트 모델에 has_one 프로젝트를 만들 수있는 방법이 있습니까?

답변

4

나는 클래스 Comment에 다음 메서드를 추가합니다 :

def project 
    self.commentable ? self.commentable.project : nil 
end 

이것은 ActivRecord의 모든 마법없이 당신에게 동일한 결과를 줄 것이다.

+0

음 ... 괜찮아요, 고마워요! –

+0

또는'commentable.try (: project)'입니다. – tokland