我有3个型号,Type,Category&产品。我正在构建一个电子商务平台,在主要产品页面上,我能够列出特定类别(男装,女装,T恤,帽子)的所有产品。
我现在要做的是遍历与特定类别相关的所有产品类型。产品类型适用于男装类别(坦克,T恤,衬衫),女装类别(连衣裙,背心,衬衫),帽子(Flexfit,Trucker,Camper)和连帽衫(套衫,拉链)。
示例输出将是 对于Mens =>坦克,T恤,衬衫。
我不确定这是否属于类型和类别之间有很多关系,因此Type.rb中的代码可能不正确。我想知道如何查询数据库以查找类别中的所有类型的产品,以及如何在种子文件中输入它们。
谢谢!
这是我的代码。
Category.rb
class Category < ActiveRecord::Base
has_many :categorizations
has_many :products, through: :categorizations
has_many :types
end
Product.rb
class Product < ActiveRecord::Base
has_many :options, dependent: :destroy
has_many :images, dependent: :destroy
has_many :categorizations
has_many :categories, through: :categorizations
has_many :types
def image_url
self.images.first.url
end
def has_image?
self.images.exists?
end
end
Type.rb
class Type < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
categories_controller.rb
class CategoriesController < ApplicationController
def show
@products = Product.includes(:categories).where('categories.name' => params[:name])
ap @products
render :layout => 'application_categories'
end
end
答案 0 :(得分:0)
查看Spree的文档和实际代码。领域模型可能比你正在寻找的要多得多,但至少你会理解一个成熟的电子商务平台在处理产品分类时的样子。 http://guides.spreecommerce.com/developer/products.html
答案 1 :(得分:0)
<强>祖先强>
这听起来像是Ancestry
gem:
#app/models/product.rb
class Product < ActiveRecord::Base
belongs_to :category
end
#app/models/category.rb
class Category < ActiveRecord::Base
has_many :products
has_ancestry
end
以下是它的工作原理:
如果您在数据库中设置了层次结构设置(通过ancestry
或closure_tree
宝石),则objects
会有一系列&#34;方法&#34;附加到它们,使您能够调用诸如object.children
这一点的重要性将在第二个
中显现出来<强>嵌套强>
您希望确保按类别过滤产品:
#config/routes.rb
resources :products, except: :show do
collection do
resources :categories, path: "" only: :show #-> domain.com/products/:id
end
end
这肯定会与您的products#show
操作冲突(暂时忽略它)。从此,您将能够使用以下内容:
<%= link_to "Hats", products_categories_path("hats") %>
这会将请求路由到以下控制器:
#app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
def show
@category = Category.find params[:id]
end
end
#app/views/categories/show.html.erb
<%= render partial: "category", locals: { category: @category } %>
<%= render partial: "category", collection: @category.children, as: :category if @category.has_children? %>
#app/views/categories/_category.html.erb
<%= category.products.each do |product| %>
<%= link_to product.name, product %>
<% end %>
<强>扩展强>
这样您就可以在视图中调用任意数量的categories
。
不可否认,我在上面概述的结构有些受限制,但同样重要的是非常重要的是给你范围&amp;能够将类别显示为树的一部分
如果您需要更多细节,我很乐意给您一些重构!