开发者

Find your way up the polymorphic tree to one parent

开发者 https://www.devze.com 2023-01-21 20:06 出处:网络
I have a simple polymorphic association #comment.r开发者_JAVA百科b belongs_to :commentable, :polymorphic => true

I have a simple polymorphic association

#comment.r开发者_JAVA百科b
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

So in IRB I can do, Post.comments, or Comment.comments.

But how can I find the parent post?

As in Comment.post ?

I can currently get their by doing a series of .commentable's. For example :

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


You can go up the list, e.g.:

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

But that can get VERY slow if they are deeply nested (n db queries). I suggest you simply store parent_post_id with comments if you need performance.

0

精彩评论

暂无评论...
验证码 换一张
取 消