2015-09-24 12 views
-1

所以,我試圖在我的rails 4應用程序中創建一個產品分類「系統」。最好的方法來分類產品在rails 4應用程序

這是我到目前爲止有:

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 

另外,我應該用什麼寶石? (awesome_nested_set,has_ancestry)

謝謝!

回答

2

這就是我在我現在生活的一個項目中所做的工作,工作得很好。

首先是類別模型,它具有名稱屬性,我使用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。請注意,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 

現在我們只包括它在一個模型,使其可分類。

的用法是這樣的

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 
+1

太謝謝你了!我將開始實施並保持更新。問題 - 類別模型不需要「有很多:分類? – Liroy

+0

正確!我錯過了那部分。編輯答案:) –

+0

真棒:)分類模型需要有一張表嗎? – Liroy

相關問題