在Rails中仅禁用collection_select的第一个选项

时间:2016-02-04 12:59:17

标签: ruby-on-rails collection-select

<%= 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>

我正在尝试将第一个选项设置为所选项目,但必须禁用。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

我在select_tag中使用它,但您需要一种分组选项:

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))

答案 1 :(得分:0)

根据http://apidock.com/rails/v4.2.1/ActionView/Helpers/FormOptionsHelper/select

  

默认情况下,post.person_id是选定的选项。指定selected:value以使用其他选择或选择:nil以取消选中所有选项。

所以你会选择:nil并删除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()' }

我使用collection_select对此进行了回合,因为该方法的文档中没有提及,但只有select的文档。

希望这有帮助!