2014-09-18 68 views
0

我困惑於拼圖。我有兩個模型,分類和發佈從recrusive has_many協會獲取記錄

類別遞歸地循環到它自我 - 它屬於父類別,並有許多子類別。在它旁邊有很多這樣的帖子,任何類別可能有職位和許多孩子類別可以有他們自己的崗位

class Post < ActiveRecord::Base 
    belongs_to :category 
end 

class Category < ActiveRecord::Base 
    belongs_to :parent_category, class_name: 'Category' 
    has_many :children_categories, class_name: 'Category', foreign_key: 'parent_category_id' 

    has_many :posts 

    def all_posts 
    # magic here 
    end 
end 

我需要實現all_posts方法範疇因此返回的ActiveRecord ::關係將所有屬於該類別及其子女的帖子統一起來。

謝謝。

p.s.我使用Rails 4.1.1和Ruby 2.1.2和PostrgreSQL 9.3

回答

1
def all_posts 
    ids = [id] 
    more_ids = [id] 
    until (more_ids = self.class.where(:parent_category_id => more_ids).pluck(:id)).empty? 
    ids += more_ids 
    end 
    Post.where(:category_id => ids) 
end