Search code examples
cssruby-on-railsruby-on-rails-4grouped-collection-select

adding class to grouped_options_for_select in Rails 4 form


I can't seem to get the class on this select to work. The grouped collection works...but not the class:

 = f.select :topic_id, grouped_options_for_select([['News',  @topics.news.order(title: :asc).collect {|v| [ v.title, v.id ] }],
        ['Opinion',    @topics.opinion.order(title: :asc).collect {|v| [ v.title, v.id ] }]]), html: {include_blank:  false , id:  'page_topic', class:  'form-control'} 

Solution

  • Try without html: key:

    = f.select :topic_id, grouped_options_for_select([['News',  @topics.news.order(title: :asc).collect {|v| [ v.title, v.id ] }],
        ['Opinion', @topics.opinion.order(title: :asc).collect {|v| [ v.title, v.id ] }]]), include_blank:  false, id: 'page_topic', class:  'form-control'
    

    P.S. Your code is very hard to read, try to extract some parts into variables, like this:

    - news_options = ['News', @topics.news.order(title: :asc).collect {|v| [ v.title, v.id ] } ]
    - opinion_options = ['Opinion', @topics.opinion.order(title: :asc).collect {|v| [ v.title, v.id ] }]    
    - options = grouped_options_for_select([news_options, opinion_options])
    = f.select :topic_id, options, include_blank: false, id: 'page_topic', class: 'form-control'