0

我有一个简单的多态关联

#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's 来获得它们。例如 :

Comment.find(1).commentable.commentable
=> Post(:id => ...
4

1 回答 1

1

您可以上列表,例如:

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

但是如果它们嵌套很深(n数据库查询),那会变得非常慢。parent_post_id如果您需要性能,我建议您只需存储评论即可。

于 2010-10-23T06:43:01.307 回答