我的rails模型的通用类别

问题描述

| 我在Rails应用程序中工作,主要要点是文章和产品。 有人为文章实现了类别。
class ArticleCategory < MainSchemaBase
  belongs_to :user
  has_many :articles,:through => :article_category_articles,:conditions => \'articles.deleted_at IS NULL\'
  has_many :article_category_articles,:conditions => \'article_category_articles.deleted_at IS NULL\'
我被要求对产品做基本上相同的事情。 我当然想干燥,但是产品属于品牌而非用户,并且我有很多产品而不是很多商品 该模型几乎是空的(某些命名范围),控制器和视图也非常依赖于上下文(文章) 可以干吗?还是我应该只复制该限制?     

解决方法

使它成为多态的:我认为,最好的方法是使用has_many_polymorphs(https://github.com/Nielsomat/has_many_polymorphs)建立多态的多对多关系,以便将单个类别应用于产品并一篇文章。
class Category
  #doesn\'t have any association fields
  has_many_polymorphs :categorizables,:from => [:products,:articles],:through => :categorizations,:dependent => :destroy 
end

class Categorization < ActiveRecord::Base
#has fields categorizable_id,categorizable_type,:category_id
  belongs_to :categorizable,:polymorphic => true
  belongs_to :category
end

class Product < ActiveRecord::Base
  #doesn\'t need anything to set up the association
end 

class Article < ActiveRecord::Base
  #doesn\'t need anything to set up the association
end 
\\“可分类\\\”有点麻烦,但是您实际上并不会使用它。您会说ѭ2​​ѭ或
@category.articles
等。