Find your way up the polymorphic tree to one parent
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.
精彩评论