這就是我在我現在生活的一個項目中所做的工作,工作得很好。
首先是類別模型,它具有名稱屬性,我使用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
模型這是任何實體之間的鏈接(產品)是categorizable
和category
。請注意,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
太謝謝你了!我將開始實施並保持更新。問題 - 類別模型不需要「有很多:分類? – Liroy
正確!我錯過了那部分。編輯答案:) –
真棒:)分類模型需要有一張表嗎? – Liroy