我有一个简单的多态关联

#comment.rb
belongs_to :commentable, :polymorphic => true
has_many :comments, :as => :commentable
#post.rb
has_many  :comments, :as => :commentable                                        
accepts_nested_attributes_for :comments, :allow_destroy => true

因此,在IRB我可以做,Post.comments,或Comment.comments。

但我怎样才能寻父的帖子?

如图Comment.post?

我现在做了一系列.commentable的的得到他们。例如:

Comment.find(1).commentable.commentable
=> Post(:id => ...
有帮助吗?

解决方案

您可以上去的名单,e.g:

class Comment < ActiveRecord::Base
    def parent_post
      c = self
      c = c.commentable while c.is_a?(Comment)
      c
    end
end

但是,这可能会变得非常慢,如果他们都深深嵌套(n的数据库查询)。 我建议你简单地存储与评论parent_post_id,如果你需要的性能。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top