문제

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 => ...
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top