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'を実行することでそれらを取得できます。例えば ​​:

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しかし、それらが深くネストされている場合( dbクエリ)、非常に遅くなる可能性があります。parent_post_idパフォーマンスが必要な場合は、コメントを付けて保存することをお勧めします。

于 2010-10-23T06:43:01.307 に答える