Grouped Select in Rails

后端 未结 2 1480
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 06:06

Simple question really - how do I use the select(ActionView::Helpers::FormOptionsHelper) with grouped options?

I have got it working with a select_tag (ActionView::H

2条回答
  •  被撕碎了的回忆
    2020-12-09 06:33

    Edit

    Correction, since you're using Arrays you'll need grouped_options_for_select

    Example:

    grouped_options = [
      ['Group 1',
        ["Item 1", "Item 2", "Item 3"]],
      ['Group 2',
        ["Item 1", "Item 2", "Item 3", "Item 4"]]
    ]
    grouped_options_for_select(grouped_options)
    

    Prints the following:

    
      
      
      
    
    
      
      
      
      
    
    

    Note that you have to provide your own select tags to wrap this. There is no select function that will do grouping for you, just this method.

    You should get over your reticence. The Rails Way (tm) to do what you ask is to use select_tag with grouped_options_for_select:

    <%= select_tag "foo[bar]", 
    grouped_options_for_select(@bars) %>
    

    This is what happens when you go off the beaten path with Rails. :)

    Here's a reference I just found on google:

    http://www.ruby-forum.com/topic/185407

提交回复
热议问题