简体   繁体   中英

Rails select options - set first option as disabled, selected

I have a select input in my Rails form -

<%= f.select :store_type_id, @storeType.map{ |type| [type.store_type.capitalize, type.id] }, {include_blank: 'Select store type'} %>

How can I make it so that the first option ('Select store type') is both disabled and selected?

The html equivalent that I'm going for would be

<option disabled selected>Select store type</option>

Thank you!

There's no way of doing this (natively) that will ensure cross-browser functionality, but here's an answer:

# on store types 
def self.options
  options = self.all.collect { |type| [type.capitalize, type.id] } 
  options.unshift(["Select Store Type", "0"])
  options
end 

# in your form 
<%= f.select :store_type_id, options_for_select(StoreType.options, :disabled => "0") %> 

However, you're depending on the browser to select a disabled input, which will contradict itself. Chrome latest goes to the next non-disabled input.

Instead, you may want to do some form validation to ensure that the value of the select is not blank.

And to keep future Ruby developers happy (and to keep yourself in line with conventions and best practices), keep in mind that Ruby endorses snake_casing your variables :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM