新手问题 [Rails] 这种情况 model 关系该如何处理?

yesmeck · 2012年08月18日 · 最后由 yesmeck 回复于 2012年08月18日 · 3685 次阅读
class Category < ActiveRecord::Base
  has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
  belongs_to :parent, :class_name => 'Category'

  has_many :products
end
class Product < ActiveRecord::Base
  belongs_to :category
end
@category = Category.find(1)
# 怎么样能让这里获取这个分类及其子分类下的所有 products?
@category.products
匿名 #1 2012年08月18日

我想严格来说,在逻辑设计上,product 的分类应该都是叶子分类

github 读下 acts_as_list | acts_as_tree 的代码,就都懂了

#1 楼 @yggg 叶子分类是什么意思?

#2 楼 @yakjuly acts_as_tree 还有那些 acts_as_nested_set 什么好想只能处理一个 model 的树关系?

匿名 #5 2012年08月18日

#3 楼 @yesmeck 就是最低一级的分类

谢谢楼上两位,之前一直想不到用什么关键词 google,好像这个方法不错,我去试试。 http://stackoverflow.com/questions/2142285/acts-as-tree-with-multiple-models

#4 楼 @yesmeck

alias self_products products

def products
  a_products ||= []
  a_products += self_products
  children.each do |c|
    a_products += c.products
  end
end

@yesmeck 是啊 你只有 Category 是树,插件里有方法可以得到 category 本身和它所有的子类。

#插件里有类似的方法
categories = Category.self_and_children(1)
products = Product.where(:category_id => categories.map(&:id))
需要 登录 后方可回复, 如果你还没有账号请 注册新账号