Categorías multinivel en Ruby on Rails y asociaciones Active Record
Frecuentes
Visto 1,211 veces
0
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
campo para 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
.
Espero entiendas lo que quiero decir.
How can reach it?
ACTUALIZACIÓN: 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
Como entendí, :foreign_key => "parent_id"
in has_many :children
has to be removed, right?
1 Respuestas
4
Have a read of Self-joining models here: http://guides.rubyonrails.org/association_basics.html#self-joins
Respondido 24 ago 12, 09:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas ruby-on-rails ruby-on-rails-3.2 or haz tu propia pregunta.
remove for :foreign_key => "parent_id" in has_many :children,crete scope :parent_category,where('parent_id is null') ,might be this is helpful - Amar