[英]Multi level categories in Ruby on Rails and Active Record associations
Ineed to create multilevel categories in Ruby on Rails. 在Ruby on Rails中创建多级类别。 So I create a model Category which has title and description and has many articles. 因此,我创建了一个具有标题和描述并包含许多文章的模型类别。
class Category
has_many :articles
end
Then I need to add parent_id
field to Category
model. 然后,我需要将parent_id
字段添加到Category
模型。 This field must be either null (if it's a parent category) or has some id (if it's a child category). 此字段必须为null(如果是父类别)或具有某些ID(如果是子类别)。 Obviously, to select any parent category it has to select Select * from Categories where parent_id=null
. 显然,要选择任何父类别,必须Select * from Categories where parent_id=null
。
I hope you understand what I mean. 我希望你明白我的意思。
How can reach it? 如何到达?
UPDATE : Thank you for your suggestion. 更新 :谢谢您的建议。 Here is what I have 这是我所拥有的
class Category < ActiveRecord::Base
belongs_to :parent, :class_name => "Category", :foreign_key => "parent_id"
has_many :children, :class_name => "Category", :foreign_key => "parent_id"
attr_accessible :description, :title
end
As I understood, :foreign_key => "parent_id"
in has_many :children
has to be removed, right? 据我了解, has_many :children
:foreign_key => "parent_id"
必须删除,对吗?
在此处阅读自我连接模型: http : //guides.rubyonrails.org/association_basics.html#self-joins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.