我记得以下几点:
从关系数据库的角度来看,这将是我将实现的内容:
从Rails建模的角度思考,我有以下内容(我避免编写对于我正在处理的这种关系/层次问题并不重要的字段):
class Product < ActiveRecord::Base
...
has_many :categories
class Category < ActiveRecord::Base
...
Here comes de doubt: How do I specify the parent_id?
有没有办法指定一个类别有一个,只有一个父ID引用另一个类别?
答案 0 :(得分:6)
这样的事情非常典型:
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