Search code examples
ruby-on-railserbactionviewdisabled-inputcollection-select

Collection_select helper cannot build disabled html tag in ruby on rails erb


Ruby on rails docs says you can add html options to tag helpers. The code below is not working. My select box cannot shown disabled. Is there anybody knows why?

<%= form.fields_for :journal_doc_analytics do |analytics| %>
    <div style="border: 2px solid red">
    <div class="field">
      <%= analytics.label :select_personel %>
      <%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, disabled: true %>      
    </div>

I also tried to write like

<%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, options = {disabled: true} %>

Or

<%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, html_options={disabled: true} %> 

https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_select

Generated HTML code doesn't include disabled option. See below. [1]: https://i.sstatic.net/HuIWE.jpg Any ideas will accepted.


Solution

  • TLDR:

    invoke the function like that (note the additional {})

    <%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, {}, disabled: true %>
    

    Explanation:

    So this one was a bit tricky. From the docs you can see that the function accepts following params:

    collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
    

    You are invoking the function like that:

    <%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, html_options={disabled: true} %>
    

    so if you look closely at the params, the html_options should be the last param that is passed and before it there is options param. So all the time you were passing disabled: true as options instead of html_options