Trouvez votre chemin jusqu'à l'arbre polymorphes à un parent
-
25-09-2019 - |
Question
J'ai une association polymorphique simple,
#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
Donc CISR je peux faire, Post.comments ou Comment.comments.
Mais comment puis-je trouver le poste parent?
Comme dans Comment.post?
Je peux en obtenir leur en faisant une série de ce .commentable
. Par exemple:
Comment.find(1).commentable.commentable
=> Post(:id => ...
La solution
Vous pouvez aller la liste, par exemple:.
class Comment < ActiveRecord::Base
def parent_post
c = self
c = c.commentable while c.is_a?(Comment)
c
end
end
Mais cela peut être très lent si elles sont profondément imbriquées (requêtes n
db).
Je vous suggère de stocker simplement parent_post_id
avec des commentaires si vous avez besoin de performances.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow