开发者

generic categories for my rails models

I am working in a rails app which main points are articles and products. Someone has implemented categor开发者_StackOverflow社区ies for articles.

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'

And I have been asked to do basically the same thing for products.

Of course I want to DRY but products belongs to brand instead of user, and I have many products instead of many articles

The model is almost empty (some named scopes), controller and views also very dependent of the context (article)

Can this be DRY? Or should I just copy the implemntation ?


Make it polymorphic: The best way, i think, is to set up a polymorphic many-to-many relationship using has_many_polymorphs (https://github.com/Nielsomat/has_many_polymorphs) so that a single category could be applied to a product and an article.

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 

"Categorizable" is a bit of a mouthful but you won't actually be using it. You'll be saying @product.categories or @category.articles etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜