2011-09-20 68 views
3

我在我的应用程序模型:has_one:通过多态 - 有可能吗?

类评论<的ActiveRecord :: Base的

belongs_to :commentable, :polymorphic => true 

类项目<的ActiveRecord :: Base的

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

课堂讨论<的ActiveRecord :: Base的

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

客位机票<的ActiveRecord :: Base的

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

一切工作正常,但有时它不是十分便利,以通过commentable从评论中获得项目,即comment.commentable.project。 有什么方法可以使评论模型中的has_one项目?

回答

4

我将在下面的方法添加到您的Comment类:

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

这会给你同样的结果而不ActivRecord所有魔法。

+0

嗯...好的决定,谢谢! –

+0

或'commentable.try(:project)'。 – tokland