2013-05-29 139 views
0

我有一個多態模型,可以涉及到本身:遞歸:包括在Rails的

class Comment < ActiveRecord::Base 
    belongs_to :commentable, polymorphic: true 
    has_many :comments, as: :commentable 
end 

這些關係很好地工作,當我試圖通過一個include調用父/子評論滿樹除聲明:

Post.find(1).include(:comments) 

這隻包括直接綁定到帖子的評論。我也許可以檢索與第二級:

Post.find(1).include(comments: :comments) 

但是,如果我想從後降,無論多麼深的嵌套所有評論什麼?這可能嗎?

回答

2

看來你想檢索一個鄰接表。 Rails沒有立即支持它,但是如果你使用postgresql,你可以使用「WITH RECURSIVE」操作符。

這插件需要照顧它:https://github.com/chrisroberts/acts_as_sane_tree

否則,你可以很容易地創建自己的PostgreSQL功能(在遷移聲明它),然後在查詢中使用它。看看:http://wiki.postgresql.org/wiki/Getting_list_of_all_children_from_adjacency_tree

WITH RECURSIVE目前不在mysql或sqlite3中實現。

+0

感謝您的徹底解答。不幸的是,我們正在使用mysql,但至少知道選項是有限的,這是很好的。 – nullnullnull