ruby-on-rails - 在下拉列表中的树层次结构中显示类别/子类别

标签 ruby-on-rails ruby-on-rails-4 gem

我有一个包含字段 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 << "&nbsp;" * 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/

相关文章:

ruby-on-rails - 104 : Connection reset by peer: nginx + rainbows + over 1 mb uploads

ruby-on-rails - 在 rspec 文件中,我得到 => Error: ActionController::RoutingError: No route matches xxxxxxx despite valid routing

ruby - 尝试生成一个随机字符串以作为 client_number 保存到 PG 表 Rails 4,PGSQL

ruby-on-rails - 如何在 Rails4 中仅显示特定子域 URL 上的文本?

ruby-on-rails - flag_shih_tzu 可以处理的最大标志数量是多少?

ruby-on-rails - 如何在rails中使用form_tag设置类属性

javascript - Stripe - 不是充值卡

ruby-on-rails - 使用 Rails 4 将自定义字段/列添加到 Devise

ruby-on-rails - Rails 可安装的 CMS 和/或博客引擎

ruby-on-rails - 升级到 Rails 3.2.6 和路由错误