我有一个包含3个字段的表类别,id名为parent_category_id
Category和子Category都与parent_category_id存储在同一个categories表中
示例:
id--------------name-------------------parent_category_id
1-类别1-无
2-子类别11-1
3-子类别12-1
4-------------Catogory2--------------------nil
5-子类别21-4
6-子类别22-4
我尝试从Category Model构建一个选择框,如下所示
选择框:
category1
subcategory11
subcategory12
category2
subcategory21
subcategory22用户可以选择category1或subcategory11
如何在Rails3.2中创建类似的下拉框
发布于 2013-09-21 04:09:15
您可以使用options_for_select帮助器方法为选择字段创建自定义选项:http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/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来设置选项标记的样式。
https://stackoverflow.com/questions/18923613
复制相似问题