ruby-on-rails - Rails 分层建模 - 多个类别

标签 ruby-on-rails database model 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? 

有什么方法可以指定一个类别只有一个引用另一个类别的父 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/

相关文章:

ruby-on-rails - 从 Rails 检查域可用性

ruby-on-rails - Link_to create with parameter before - ForbiddenAttributesError 现在

ruby-on-rails - 在脚本中使用不带 Rails 的 ActiveRecord 3.1

c# - 无法将类型 'System.Linq.IQueryable<Project.Models.TaskTimeLine>' 隐式转换为 'Project.Models.TaskTimeLine'

c# - 将复选框列表绑定(bind)到数据模型中的字典

java - neo4j modell 与 n 个属性的关系 vs n 与一个属性的关系

ruby-on-rails - 带条件的 to_json :except in rails

java - 如何将 ResultSet 转换为 DTO ArrayList

database - 使用Elasticsearch聚合查找桶的并集或相交

database - 关系的候选键的最小数量?