views:

17

answers:

1

I have a simple polymorphic association

#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

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 => ...
+1  A: 

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.

glebm
GREAT IDEA about parent_post_id!! Also yes, its so slow, my grandma could flip flap jacks on her back faster than that.
Trip
you really shouldnt program when you are stoned dude... (**cough** **cough**) :)
glebm
What a night...
Trip