设置会好很多
@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
我自己没有在 Spree 项目中实现这个,这取决于你使用 Rails 3.0.3+ 版本,但这是我建议的基本方法。