【问题标题】:Find your way up the polymorphic tree to one parent在多态树上找到一个父节点
【发布时间】:2010-10-23 06:31:32
【问题描述】:

我有一个简单的多态关联

#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.cmets 或 Comment.cmets。

但是我怎样才能找到父帖子?

就像在 Comment.post 中一样?

我目前可以通过执行一系列.commentable 来获得它们。例如:

Comment.find(1).commentable.commentable
=> Post(:id => ...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 polymorphic-associations arel


    【解决方案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 与 cmets 一起存储。

    【讨论】:

    • 关于 parent_post_id 的好主意!也是的,它太慢了,我奶奶可以比这更快地翻转她背上的襟翼千斤顶。
    • 当你被石头砸死的时候,你真的不应该编程......(咳嗽 咳嗽):)
    猜你喜欢
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多