你通常會這樣做的東西是建立一個分類樹,它將與產品相關聯,允許你將產品分組在一起。分類和產品之間的多對多關係可讓您將產品與多個組關聯,因此T恤可能位於類別>男士>襯衫以及場合>休閒類別下。
# app/models/taxonomy.rb
class Taxonomy < ActiveRecord::Base
has_many :taxonomies
has_and_belongs_to_many :products
end
# app/models/product.rb
class Product < ActiveRecord::Base
has_and_belongs_to_many :taxonomies
end
然後分類/產品
rails g migration create_products_taxonomies
和編輯
def change
create_table(:products_taxonomies, :id => false) do |t|
t.references :product
t.references :taxonomy
end
end
從那裏,你基本上會在數據庫中創建3個分類單位,各1之間的連接表遷移的部分,然後創建分類標準並建立子級別。當您創建產品時,將正確的分類標準分配給產品和您的產品。
種子文件可能看起來像......
Taxonomy.create!(:name => "Category").tap do |category|
category.taxonomies.create!(:name => "Men").tap do |men|
men.taxonomies.create!(:name => "Shirt")
men.taxonomies.create!(:name => "Trousers")
end
# and so on for each category
end
然後,當你創建一個產品,你可以將其與關聯分類和使用分類拉起的那些與它相關聯的產品列表。