如何将具有与之关联的特定狂欢分类的所有产品呈现到模板上

时间:2015-03-03 17:12:36

标签: ruby-on-rails spree

进一步了解Spree教程,我们希望列出所有产品及其子项,其分类名称为“Soaps”,以显示在Soaps产品页面上。查看数据库(表:spree_taxons),我们发现Soaps的分类单元ID是“1”,它也恰好是父类。

这是我们迄今为止创建的内容:/root/mystore/spree_simple_sales/app/controllers/spree/home_controller_decorator.rb

module Spree
   HomeController.class_eval do

#rescue_from ActiveRecord::RecordNotFound, :with => :render_404
helper 'spree/taxons'
helper 'spree/products'
respond_to :html

def sale
  @products = Product.joins(:variants_including_master).where('spree_variants.sale_price is not null').uniq
    end

def soaps
  @products = Product.joins(:variants_including_master).where('spree_taxons.id == 1').uniq
    end

 end
end

这是我们在模板文件中的内容: /root/mystore/app/views/spree/home/soaps.html.erb

<% content_for :sidebar do %>
  <div data-hook="homepage_sidebar_navigation">
    <%= render :partial => 'spree/shared/taxonomies' %>
  </div>
<% end %>

<div data-hook="homepage_products">
<img src="http://192.168.2.228:3000/assets/store/soaps_cover_photo.jpg" />

<p>Important information regarding the Soaps taxon goes here.</p>
<!-- code to render all products with soaps taxon (aka, taxon ID=1) -->
<%= render 'spree/shared/products', :products => @products %>
</div>

我们认为我们的代码编写错误。有人能告诉我们正确显示Soaps分类产品及其所有孩子所需的语法吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

我们可以通过在home_controller_decorator.rb文件中使用以下代码来实现此功能。

def soaps
      @products = Spree::Product.in_taxons(1)
      @taxonomies = Spree::Taxonomy.includes(root: :children)
    end