在Rails 3.2的单个选择框中显示类别和子类别

时间:2013-09-20 18:35:32

标签: ruby-on-rails parent-child dropdownbox

我有一个包含3个字段的表类别 ID 名称 parent_category_id

类别和子类别都存储在与parent_category_id

相同的类别表中

示例:

ID --------------名称------------------- parent_category_id

1 -------------组别-------------------零

2 ------------ subCategory11 ---------------- 1

3 ------------ subcategory12 ---------------- 1

4 ------------- Catogory2 --------------------零

5 -------------- subCategory21 --------------- 4

6 -------------- subCategory22 --------------- 4

我试图像这样

从类别模型中构建一个选择框

选择框:

category1
    subcategory11
    subcategory12
category2
    subcategory21
    subcategory22

用户可以选择category1或subcategory11

如何制作Rails3.2中的下拉框

2 个答案:

答案 0 :(得分:1)

您可以使用options_for_select辅助方法为您的选择字段创建自定义选项: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select

创建数组的递归方法可以传递给options_for_select,如下所示:

def subcat_prefix(depth)
  (" " * 4 * depth).html_safe
end

def category_options_array(categories=[], parent_id=nil, depth=0)
  Category.where(parent_category_id: parent_id).order(:id).each do |category|
    categories << [subcat_prefix(depth) + category.name, category.id]
    category_options_array(categories, category.id, depth+1)
  end

  categories
end

要使用该方法,例如:

select_tag :category_id, options_for_select(category_options_array)

请注意,这适用于多个级别的子类别。要更改选择字段的外观,可以不同地定义subcat_prefix方法,或使用类和CSS来设置选项标记的样式。

答案 1 :(得分:0)

我为此使用了“awesome_nested_set”gem。它使用起来非常顺畅。

gem'awesome_nested_set'

如果您已经有一个包含parent_id的类别表,那么将以下3列添加到您的表

add_column :categories, :lft, :integer
add_column :categories, :rgt, :integer
add_column :categories, :depth, :integer

如果你有自定义父(something_parent_id)id而不是parent_id,那么作为自定义parent_id的选项传递,如:

acts_as_nested_set:parent_column =&gt; :parent_category_id

当你想用作选择框时

 f.select :parent_id, nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" } 

or

 select_tag 'parent_id', options_for_select(nested_set_options(Category) {|i| "#{'-' * i.level} #{i.name}" } )