あなたがに似て特定のカテゴリの子供を取得することができますと仮定すると:あなたに続いて
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
:
has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
は、すべての子を取得し、レベルによってそれぞれをインデントするカテゴリのメソッドを作成します。表示:
<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%テストしていませんが、私はそれがうまくいくはずです...