在 rails 4 个应用程序中对产品进行分类的最佳方式

Best way to categorize products in rails 4 app

因此,我正在尝试在我的 rails 4 应用程序中创建产品分类 'system'。

这是我目前的情况:

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

此外,gem 我应该使用什么? (awesome_nested_set, has_ancestry)

谢谢!

这是我在我的一个项目中所做的,该项目现在正在运行并且运行良好。

首先是类别模型,它有一个名称属性,我正在使用 gem acts_as_tree 这样类别就可以有子类别。

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

然后我们将添加一个叫做 categorical 模型的东西,它是 categorizablecategory 之间的任何实体(产品)之间的 link。请注意,categorizable 是多态的。

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

  validates_presence_of :category, :categorizable
end

现在,一旦我们设置了这两个模型,我们将添加一个关注点,可以使自然界中的任何实体 categorizable,无论是产品、用户等

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

现在我们只需将其包含在模型中以使其可分类。

class Product < ActiveRecord::Base
  include Categorizable
end

用法是这样的

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