沿着多态树找到一个父级的路径
我有一个简单的多态关联
#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 => ...
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 => ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以向上查看列表,例如:
但是如果它们深度嵌套(
n
db 查询),那么速度可能会非常慢。如果您需要性能,我建议您只需存储
parent_post_id
和评论。You can go up the list, e.g.:
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.