我想使用form.select创建一个带选项的optgroup。除了“选择一个类别”之外,我无法在下拉列表中看到任何内容。结果HTML显示它将select标记嵌套在另一个标记内。是否有选项不通过grouped_collection_select生成最里面的选择标记?
产品/ _form.html.erb
<%= form.select :category_id, grouped_collection_select(:product, :category_id, Category.top_level, :sub_categories, :name, :id, :name),
{ prompt: 'Select a category'},
{ id: :product_category } %>
category.rb
has_many :products
has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
scope :top_level, -> { where(parent_id: nil) }
product.rb
belongs_to :category
<select id="product_category" name="product[category_id]">
<option value="">Select a category</option>
<select name="product[category_id]" id="product_category_id">
<optgroup label="Category 1">
<option value="4">Sub Category A</option>
<option value="5">Sub Category B</option>
</optgroup>
<optgroup label="Category 2">
<option value="6">Sub Category A</option>
<option value="7">Sub Category B</option>
</optgroup>
</select>
</select>
答案 0 :(得分:0)
对于其他感兴趣的人,下面的语法给了我预期的HTML输出。
<%= form.grouped_collection_select(:category_id, Category.top_level, :sub_categories, :name, :id, :name,
{ prompt: 'Select a category'},
{ id: :product_category }) %>