[英]Ruby on Rails - Active Record Associations for Multi-tenant Account and User
[英]Multi level categories in Ruby on Rails and Active Record associations
在Ruby on Rails中创建多级类别。 因此,我创建了一个具有标题和描述并包含许多文章的模型类别。
class Category
has_many :articles
end
然后,我需要将parent_id
字段添加到Category
模型。 此字段必须为null(如果是父类别)或具有某些ID(如果是子类别)。 显然,要选择任何父类别,必须Select * from Categories where parent_id=null
。
我希望你明白我的意思。
如何到达?
更新 :谢谢您的建议。 这是我所拥有的
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
据我了解, has_many :children
:foreign_key => "parent_id"
必须删除,对吗?
在此处阅读自我连接模型: http : //guides.rubyonrails.org/association_basics.html#self-joins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.