我有以下想法:
- 一个产品可以有多个类别
- 一个类别可以在不同的产品中。
- 如果类别不是一般类别(在这种情况下,父类别将为零),则该类别具有父类别(类别)
从关系数据库的角度来看,这将是我要实现的东西:
- 表格产品
- 表 product_category(作为主键:product_id、category_id)
- 表 类别(带有引用类别的 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?
最佳答案
像这样的事情是相当典型的:
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
关于ruby-on-rails - Rails 分层建模 - 多个类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868767/