2012-01-12 31 views
2

Rails noob在這裏試圖在客戶的Spree商店中調整一些東西。按字母順序排序分類(品牌)

側邊欄需要包含產品品牌列表,並且我有品牌作爲分類。

shared/_taxonomies.html.erb視圖包含:

<% get_taxonomies.each do |taxonomy| %> 
    <% if taxonomy.name == 'Brand' %> 
     <h3 class='taxonomy-root'><%= t(:shop_by_taxonomy, :taxonomy => taxonomy.name.singularize) %></h3> 
     <%= taxons_tree(taxonomy.root, @taxon, Spree::Config[:max_level_in_taxons_menu] || 1) %> 
    <% end %> 
    <% end %> 

我加入了if taxonomy.name == 'Brand'碼擺脫類別。 (我希望有一個更清潔的方式?)

我如何可以按字母順序列出taxons(品牌)?

Spree 0.70.3。

回答

4

它要好得多設置

@brand_taxonomy = Taxonomy.where(:name => 'Brand').first 

在一個共同的控制器,最有可能的application_controller.rb如果分類顯示在大多數/所有頁面,然後只是去:

<h3 class='taxonomy-root'><%= t(:shop_by_taxonomy, :taxonomy => @brand_taxonomy.name.singularize) %></h3> 
<%= taxons_tree(@brand_taxonomy.root, @taxon, Spree::Config[:max_level_in_taxons_menu] || 1) %> 

從而完全消除循環和條件。

不幸的是,taxons_tree助手直接調出頂級分類學的孩子,所以爲了獲得按名稱排序的孩子,你不得不重寫幫手,說在application_helpers.rb爲:

def my_taxons_tree(root_taxon, current_taxon, max_level = 1) 
    return '' if max_level < 1 || root_taxon.children.empty? 
    content_tag :ul, :class => 'taxons-list' do 
    root_taxon.children.except(:order).order(:name).map do |taxon| 
     css_class = (current_taxon && current_taxon.self_and_ancestors.include?(taxon)) ? 'current' : nil 
     content_tag :li, :class => css_class do 
     link_to(taxon.name, seo_url(taxon)) + 
     taxons_tree(taxon, current_taxon, max_level - 1) 
     end 
    end.join("\n").html_safe 
    end 
end 

關鍵的變化是將.except(:order).order(:name)添加到助手的孩子檢索中。

最終的視圖代碼如下所示:

<h3 class='taxonomy-root'><%= t(:shop_by_taxonomy, :taxonomy => @brand_taxonomy.name.singularize) %></h3> 
<%= my_taxons_tree(@brand_taxonomy.root, @taxon, Spree::Config[:max_level_in_taxons_menu] || 1) %> 

application_controller.rb你要補充:

before_filter :set_brand_taxonomy 

def set_brand_taxonomy 
    @brand_taxonomy = Taxonomy.where(:name => 'Brand').first 
end 

我還沒有在施普雷項目實施自己這一點,這取決於你使用Rails 3.0.3+版本,但這是我建議的基本方法。

+0

感謝您的非常詳細的答案。它似乎並不像現在這樣工作。由於關於未定義變量的錯誤,我在'my_taxons_tree(brand_taxonomy.root')中添加了一個'@'符號,然後,我爲此行獲得了'nil:NilClass'的未定義方法'root'我的application_controller。 rb:http://pastie.org/3178498(我刪除了視圖中的h3行,因爲這也給出了一個錯誤。) – 2012-01-13 14:42:15

+0

更正了缺少'@';對不起,所以如果你去:'rails console' 然後輸入:'Taxonomy.where?(:名稱=>「品牌」)' ...是什麼返回 這聽起來像有 – Cyberfox 2012-01-14 10:55:54

+0

命名爲「品牌」無父分類...此外,你在'application_controller.rb'中添加了'my_taxons_tree'幫助器方法;我建議你把它放到application_helper.rb中,它在'app/helpers'中,如果你確定你想把它放到application ion_controller,你需要在控制器的頂部添加'helper_method:my_taxons_tree',並將它放在一個專用塊中(只需在'my_taxons_tree'定義之前放一行'private'。 Rails更像是將它放在'app/helpers/application_helper.rb'中。 – Cyberfox 2012-01-14 11:02:12