Rails分层建模 - 多个类别

Nob*_*ita 2 database model ruby-on-rails hierarchy

我有以下几点:

  1. 一个产品可以有多个类别
  2. 一个类别可以在不同的产品中.
  3. 有父(类别),如果它不是一个普通类(在这种情况下,父母将无)

从关系数据库的角度来看,这将是我将实现的内容:

  1. 产品
  2. product_category(作为主键:product_id,category_id)
  3. 类别(带有引用类别的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? 
Run Code Online (Sandbox Code Playgroud)

有没有办法指定一个类别有一个,只有一个父ID引用另一个类别?

Jor*_*ing 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.
Run Code Online (Sandbox Code Playgroud)

或者,您可以给出最后两个不同的名称,例如:

belongs_to :parent,   :class_name => :category
has_many   :children, :class_name => :category
Run Code Online (Sandbox Code Playgroud)