简体   繁体   中英

Multi level categories in Ruby on Rails and Active Record associations

Ineed to create multilevel categories in 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. This field must be either null (if it's a parent category) or has some id (if it's a child category). Obviously, to select any parent category it has to select 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?

在此处阅读自我连接模型: http : //guides.rubyonrails.org/association_basics.html#self-joins

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM