如何在rails视图中输出类别和子类别?像这样:
我的 schema.rb :
create_table "categories", force: :cascade do |t|
t.integer "title"
t.boolean "state", default: true
t.integer "parent_id" # id of parent category
end
我的 categories_controller.rb
def show
@category = Category.find(params[:id])
#child categories of current parent category
@child_categories = Category.where(parent_id: @category.id)
#subchild categories of current parent category
@child_categories.each do |category|
@subchild_categories = Category.where(parent_id: category.id)
end
end
我的 show.html.erb
<% if @child_categories.any? %>
<ul>
<% @child_categories.each do |child| %>
<li>
<%= child.title %>
<ul>
<% @subchild_categories.each do |subchild| %>
<li><%= subchild.title %></li>
<% end %>
</ul>
</li>
<% end %>
</ul>
<% end %>
现在我得到这样的东西:
答案 0 :(得分:1)
#try this:
def show
@category = Category.find(params[:id])
@child_categories = Category.where(parent_id: @category.id)
@subchild_categories = {}
@child_categories.each do |category|
@subchild_categories[category.title] = Category.where(parent_id: category.id)
end
end
#and in view:
<% @child_categories.each do |child| %>
<li>
<%= child.title %>
<ul>
<% @subchild_categories[child.title].each do |subchild| %>
<li><%= subchild.title %></li>
<% end %>
</ul>
</li>
<% end %>
答案 1 :(得分:0)
您可以在调用children
的{{1}}模型中创建Category
方法然后只使用它
where(parent_id: id)
然后您可以根据需要在视图中使用它:
def self.children
where(parent_id: id)
end