Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 222
skwidbreth Avatar asked Sep 25 '22 13:09

skwidbreth


1 Answers

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

like image 92
Josh Brody Avatar answered Sep 28 '22 05:09

Josh Brody