如何解决我的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
等。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。