Ruby on rails 如何为树标记父元素?
请帮忙解决这个问题 我使用gem'awesome_嵌套_set'。我为模型类别制作了CRUD,并填充了以下DB值:Ruby on rails 如何为树标记父元素?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,请帮忙解决这个问题 我使用gem'awesome_嵌套_set'。我为模型类别制作了CRUD,并填充了以下DB值: science = Category.create!(:title => 'Science') physics = Category.create!(:title => 'Physics') physics.move_to_child_of(science) gravity = Category.create!(:title => 'Gravity') gra
science = Category.create!(:title => 'Science')
physics = Category.create!(:title => 'Physics')
physics.move_to_child_of(science)
gravity = Category.create!(:title => 'Gravity')
gravity.move_to_child_of(physics)
结果,我的树看起来:
Science
-- Physics
-- -- Gravity
在索引模板中,我输出所有根元素:
类别\u controller.rb:
def index
@categories = Category.roots
end
def show
@categories = Category.find_by_id(params[:id]).self_and_descendants
end
index.html.erb:
<% @categories.each do |category| %>
<td><%= link_to category.title, category %></td>
<% end %>
<% @categories.each do |category| %>
<% if category.root? %>
<strong><%= category.title %></strong>
<% else %>
<div style="padding-left: <%= category.level %>0px"><%= link_to category.title, category %></div>
<% end %>
<% end %>
show.html.erb:
<% @categories.each do |category| %>
<td><%= link_to category.title, category %></td>
<% end %>
<% @categories.each do |category| %>
<% if category.root? %>
<strong><%= category.title %></strong>
<% else %>
<div style="padding-left: <%= category.level %>0px"><%= link_to category.title, category %></div>
<% end %>
<% end %>
您的第一个类别并不总是根。在这种情况下,“根”是指实际的根类别,而不仅仅是给定上下文中最顶层的类别。您必须更改显示逻辑,使其不再依赖于
root?
方法,而只需突出显示第一个类别,这似乎是您的实际意图:
<strong><%= categories.first.title %></strong>
<% @categories[1..-1].each do |category| %>
<div style="padding-left: <%= category.level %>0px"><%= link_to category.title, category %></div>
<% end %>
谢谢,但是