我一直在关注HABTM Railscast,并希望对其进行扩展。
Railscast方法非常适合在产品中添加类别。但是,可以说我有(说)五种将产品按不同维度分类的方法(这些方法有时会发生变化)。
使用提供的解决方案,每次添加新的“尺寸”时,我都需要向应用程序中再添加2个模型。
本质上,我想从类似的模型中迁移:
产品:卡坦定居者
类别:棋盘游戏,玩具等
到:
产品:卡坦定居者
类别:桌游,玩具等
年龄范围
:1-10,11-20费用:高
Railscast解决方案在这里:http ://railscasts.com/episodes/17-habtm-checkboxes-revised?view=comments
现有解决方案,有待扩展:
产品.rb
has many categorisations
has many categories, through categorisations
Categorisation.rb
belongs to many products
belongs to many categories
Category.rb
has many products, through categorisation
has many categorisations
我可以做类似的事情:
产品.rb
has many AgeRangeCategorisations
has many AgeRanges, through AgeRangeCategorisations
AgeRangeCategorisation.rb
belongs to many products
belongs to many AgeRanges
AgeRange.rb
has many products, through AgeRangeCategorisation
has many AgeRangeCategorisations
和
产品.rb
has many CostCategorisations
has many Costs, through CostCategorisations
CostCategorisation.rb
belongs to many products
belongs to many costs
Cost.rb
has many products, through CostCategorisation
has many CostCategorisations
但是,感觉并不像Rails为每种“类别类型”创建新模型的方式。
我认为符合以下几点:
产品.rb
has many CategoryTypes
has many CategoryTypes, through CategoryTypeCategorisations
CategoryTypeCategorisations.rb
belongs to many Products
belongs to many CategoryTypes
CategoryType.rb
belongs to many CategoryTypeCategorisations
belongs to many categorisations
has many categories, through categorisations
Categorisation.rb
has many products
has many categories
Category.rb
has many products, through categorisation
has many categorisations
CategoryType是维(年龄,成本等),类别是CategoryType的有效答案列表。
现在,这与这么多“属于”和“有很多人在浮动”变得有些混乱
这是解决此问题的正确方法吗?我还能如何处理呢?
您的最后一个变体是解决此问题的一种方法。当然,您不希望每个类别类型都有一个类。除非那些类别类型可能带有很多额外的业务逻辑来定义产品的“行为”,否则这种情况下,诸如“单表继承”之类的建模将是更好的方法。但是当您描述它时,我想它们更像是标记,主要是一些附加描述。(如果只有两种或三种类别类型,并且保持这种方式,那么类别的数量就没多大关系了,但是如果您计划得更多,我将避免这种情况)
至少出于完整性考虑,我将要提到一种替代方法,因为这将为您节省一张表,并且这样也就不那么复杂了。这将只是将这些类别建模为层次结构,其中您的类别类型是父类别,而类别是子类别。
Category
- Board Games
- Toy
Age Range
- 1-10
- 11-20
Cost
- Low
- Medium
- High
这更像是解决此问题的“经典”方法。
另外(尤其是如果您有很多产品和类别)(也许使用某些多面搜索引擎(Solr,Elastic,Sphinx ...)或具有类似功能的NOSql存储)可以使按多个属性进行搜索变得非常容易。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句