Reputation: 13328
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?
Upvotes: 0
Views: 1258
Reputation: 7220
Have a read of Self-joining models here: http://guides.rubyonrails.org/association_basics.html#self-joins
Upvotes: 4