Nob*_*ita 2 database model ruby-on-rails hierarchy
我有以下几点:
从关系数据库的角度来看,这将是我将实现的内容:
从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引用另一个类别?
像这样的东西很典型:
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)
| 归档时间: |
|
| 查看次数: |
1919 次 |
| 最近记录: |