Disable only first option of collection_select in Rails

1.5k Views Asked by At
<%= f.collection_select :admin_attachment_id, @data['attachments'], :id, :title, { prompt: 'Select banner' }, { class: 'form-control', required: '', 'ng-model': 'banner.admin_attachment_id', 'ng-change': 'get_attachment_thumbnail()', disabled: 'Select banner', selected: '' } %>

Renderized:

<select class="form-control ng-pristine ng-untouched ng-invalid ng-invalid-required" required="required" ng-model="banner.admin_attachment_id" ng-change="get_attachment_thumbnail()" name="admin_banner[admin_attachment_id]" id="admin_banner_admin_attachment_id">
    <option value="">Select banner</option>
    <option value="89">Banner 1</option>
    <option value="94">Banner 2</option>
    <option value="114">Banner 3</option>
</select>

I'm trying to set the first option as selected item, but must be disabled. How can I do this?

2

There are 2 best solutions below

0
On

I'm using it in a select_tag, but you need a form of grouped options:

grouped_options = [ 
  [ 'Select banner',
    [
     ['Banner 1', '89'],
     ['Banner 2', '94'],
     ['Banner 3', '114']
    ]
  ]

select_tag('admin_banner[admin_attachment_id]', grouped_options_for_select(:grouped_options))
0
On

According to http://apidock.com/rails/v4.2.1/ActionView/Helpers/FormOptionsHelper/select

By default, post.person_id is the selected option. Specify selected: value to use a different selection or selected: nil to leave all options unselected.

So you would put in selected: nil and remove disabled:

<%= f.collection_select :admin_attachment_id, @data['attachments'], :id, :title, { prompt: 'Select banner', selected: nil }, { class: 'form-control', required: '', 'ng-model': 'banner.admin_attachment_id', 'ng-change': 'get_attachment_thumbnail()' }

I went round and round on this with collection_select as this is not mentioned in the docs for that method but only the one for select.

Hope this helps!