【问题标题】:Rails hierarchical modelling - Multiple categoriesRails 分层建模 - 多个类别
【发布时间】:2012-01-15 09:38:35
【问题描述】:
我有以下想法:
- 一个产品可以有多个类别
- 一个类别可以属于不同的产品。
- 如果 category 不是一般类别,则它有一个父级(类别)(在这种情况下,父级将为 nil)
从关系数据库的角度考虑,我会这样实现:
- 表产品
- 表product_category(作为主键:product_id、category_id)
- 表category(如果是“一般”类别,则使用 parent_id 引用类别或 nil)
从 Rails 建模的角度考虑,我有以下几点(我避免编写对我正在处理的这个关系/层次问题并不重要的字段):
class Product < ActiveRecord::Base
...
has_many :categories
class Category < ActiveRecord::Base
...
Here comes de doubt: How do I specify the parent_id?
有没有办法指定一个类别有一个,并且只有一个父 ID 引用另一个类别?
【问题讨论】:
标签:
ruby-on-rails
database
model
hierarchy
【解决方案1】:
这样的事情相当典型:
class Product < ActiveRecord::Base
has_many :categories, :through => :products_categories
# A has_and_belongs_to_many association would also be fine here if you
# don't need to assign attributes to or perform any operations on the
# relationship record itself.
end
class Category < ActiveRecord::Base
has_many :products, :through => :products_categories
belongs_to :category
has_many :categories # Optional; useful if this is a parent and you want
end # to be able to list its children.
或者,您可以给最后两个不同的名称,例如:
belongs_to :parent, :class_name => :category
has_many :children, :class_name => :category