Best way to categorize products in rails 4 app

爷,独闯天下 提交于 2019-12-13 08:29:09

问题


So, I'm trying to create a product categorization 'system' in my rails 4 app.

Here's what I have so far:

class Category < ActiveRecord::Base
  has_many :products, through: :categorizations
  has_many :categorizations
end

class Product < ActiveRecord::Base
  include ActionView::Helpers

  has_many :categories, through: :categorizations
  has_many :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :category
  belongs_to :product
end

Also, what gem should I use? (awesome_nested_set, has_ancestry)

Thanks!


回答1:


This is what I did in one of my projects which is live right now and works very well.

First the category model, it has a name attribute and I am using a gem acts_as_tree so that categories can have sub categories.

class Category < ActiveRecord::Base
  acts_as_tree order: :name
  has_many :categoricals
  validates :name, uniqueness: { case_sensitive: false }, presence: true
end

Then we will add something called a categorical model which is a link between any entity(products) that is categorizable and the category. Note here, that the categorizable is polymorphic.

class Categorical < ActiveRecord::Base
  belongs_to :category
  belongs_to :categorizable, polymorphic: true

  validates_presence_of :category, :categorizable
end

Now once we have both of these models set up we will add a concern that can make any entity categorizable in nature, be it products, users, etc.

module Categorizable 
  extend ActiveSupport::Concern

  included do
    has_many :categoricals, as: :categorizable
    has_many :categories, through: :categoricals
  end

  def add_to_category(category)
    self.categoricals.create(category: category)
  end

  def remove_from_category(category)
    self.categoricals.find_by(category: category).maybe.destroy
  end

  module ClassMethods
  end
end

Now we just include it in a model to make it categorizable.

class Product < ActiveRecord::Base
  include Categorizable
end

The usage would be something like this

p = Product.find(1000) # returns a product, Ferrari
c = Category.find_by(name: 'car') # returns the category car

p.add_to_category(c) # associate each other
p.categories # will return all the categories the product belongs to


来源:https://stackoverflow.com/questions/32761007/best-way-to-categorize-products-in-rails-4-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!