创建具有树结构的模型 [英] Creating a model that has a tree structure

查看:32
本文介绍了创建具有树结构的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有树状结构的类别.我试图通过为每个人定义一个父级来将它们链接在一起.(我不知道如何调用属性 parent 所以它现在只是 category,但它意味着父级).

I have categories that are in a tree structure. I am trying to link them together by defining a parent for each one. (I couldn't figure out how to call the property parent so it's just category for now, but it means the parent).

class Category < ActiveRecord::Base

    has_one :category # the parent category

end 

但这段关系以错误的方式结束.

But the relationship ends up the wrong way around.

getter 函数位于子类别(正确)上,但 category_id 存储在父类别上:

The getter function is on the child category (correctly) but the category_id is stored on the parent:

parent = Category.create(:name => "parent")
child = Category.create(:name => "child", :category => parent)

parent.id # 1
child.id # 2

child.category_id # nil
parent.category_id # 2

child.category.name # "parent" (!!)

父母需要能够有多个孩子,所以这是行不通的.

The parent needs to be able to have multiple children so this isn't going to work.

推荐答案

您正在寻找的是自联接.查看 Rails 指南的这一部分:http://guides.rubyonrails.org/association_basics.html#self-joins

What you're looking for is self joins. Check this section of the Rails guide out: http://guides.rubyonrails.org/association_basics.html#self-joins

class Category < ActiveRecord::Base
  has_many :children, class_name: "Category", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Category"
end

每个类别都将belong_to成为父类别,甚至是您的父类别.您可以创建您的最高级别类别都属于的单个类别父级,然后您可以在应用程序中忽略该信息.

Every Category will belong_to a parent, even your parent categories. You can create a single category parent that your highest level categories all belong to, then you can disregard that information in your application.

这篇关于创建具有树结构的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆