我正在尝试使用sinatra和activereord (使用sinatra-activerecord gem)来创建一个在线商店,但是我在想如何生成类别(子类别和其他东西)的“树”时遇到了一些麻烦。
类别数据库只包含类别名称和parent_id,活动记录模型如下所示:
class Category < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
has_many :sub_categories, :class_name => 'Category',
:foreign_key => 'parent_id', :dependent => :destroy
has_many :products, :dependent => :destroy
belongs_to :parent_category, :class_name => 'Category'
end我该如何让它成为我可以在模板中作为嵌套的ul标记的东西(如果它有用处,我会使用haml )?
很抱歉问了这么多问题,但我从来没有真正使用过这种类型的数据结构。
发布于 2011-07-09 11:12:07
我想通了。它使用HAML helper,如果存在current_page,还会将current类应用于右侧的元素。这是帮助者
module Haml::Helpers
def categories_menu(parent=nil, current_page=false)
categories = Category.where(:parent_id => parent)
haml_tag :ul do
categories.each do |category|
haml_tag :li, :class => ("current" if current_page == category.id) do
haml_tag :a, :href => "/category/#{category.id}", :class => ("submenu" unless category.sub_categories.empty?) do
haml_concat(category.name)
end
unless category.sub_categories.empty?
categories_menu(category.id)
end
end
end
end
end
end在haml模板中使用它,如下所示:
#test
- categories_menu(nil, (@category.id if defined? @category))不能保证它能与其他任何人的应用程序一起工作。
https://stackoverflow.com/questions/6606855
复制相似问题