我坚持拼图 . 我有两个型号,分类和邮政
类别以递归方式循环到它自身 - 它属于父类别并且具有许多子类别 . 因此,它有许多职位,任何类别都可以有帖子和许多儿童类别可以拥有自己的职位
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
我需要实现Category的all_posts方法,因此它返回ActiveRecord :: Relation,它将属于该类别及其子节点的所有帖子联合起来 .
谢谢 .
附:我使用Rails 4.1.1和Ruby 2.1.2以及PostrgreSQL 9.3
1 回答