我有一个包含字段 id、name 和 parent_id 的类别表。根类别的 parent_id 为 0。现在我想在下拉列表中显示类别列表,结构如下:
root_category
first_sub_category
sub_sub_category
another_sub_sub_category
second_sub_category
another_root_category
first_sub_category
second_sub_category
这是我的 Controller :
def new
@category = Category.new
end
这是 View :
<%= f.label :parent_category %>
<% categories = Category.all.map{|x| [x.name] + [x.id]} %>
<%= f.select(:parent_id, options_for_select(categories), {}, class: 'form-control') %>
请帮忙。
最佳答案
假设您可以获得给定类别的子类,类似于:
has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
为类别创建一个方法以获取所有子级并按级别缩进:
def all_children2(level=0)
children_array = []
level +=1
#must use "all" otherwise ActiveRecord returns a relationship, not the array itself
self.children.all.each do |child|
children_array << " " * level + category.name
children_array << child.all_children2(level)
end
#must flatten otherwise we get an array of arrays. Note last action is returned by default
children_array = children_array.flatten
end
那么在你看来:
<select>
<option></option>
<% root_categories.each do |category| %>
<option><%=category.name%></option>
<% category.all_children2.each do |child| %>
<option><%=child.html_safe%></option>
<% end %>
<% end %>
</select>
我还没有 100% 测试过这个,但我确实建议它应该可以工作......
关于ruby-on-rails - 在下拉列表中的树层次结构中显示类别/子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442105/