我有一个类别表,其中包含字段 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
这是我的控制器:
def new
@category = Category.new
end
这是视图:
<%= 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% 测试过这个,但我确实建议它应该有效......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)