remove a blank option of select field that was generated by SimpleForm

Ruby on-Rails

Ruby on-Rails Problem Overview


I have this piece of code:

= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"]

Choices["Categories"] is just a hash of key=>value pairs.

SimpleForm generates a select field with all needed options, but it also makes the first option blank.
This blank option is present in all select fields that were generated by SimpleForm.

But I don't want to have a blank option. Is there a way to get rid of it?

Something like :allow_blank_option => false?

I tried to make a presence validation of this attribute hoping that SimpleForm will detect it, but it didn't help.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can pass a include_blank: false, include_hidden: false option:

= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"], include_blank: false, include_hidden: false

Solution 2 - Ruby on-Rails

or you can customize call back action in your model to remove any empty string in the array parameter, assuming a parameter with the name "types":

before_validation :remove_empty_string

def remove_empty_string
  types.reject! { |l| l.empty? }
end

Solution 3 - Ruby on-Rails

To remove a blank field from select it is necessary to show the selected so add selected: 1 Then set prompt to anything like prompt: "Please Select" The final output will be <%= select("social_links",:option_id, Option.all.collect {|p| [ p.name, p.id ] },{ selected: 1 , prompt: "Please Select"}, { class: 'form-control' , required:true})%>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSerge VinogradoffView Question on Stackoverflow
Solution 1 - Ruby on-RailsDylan MarkowView Answer on Stackoverflow
Solution 2 - Ruby on-RailsAntonio JhaView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSoumitra SarkarView Answer on Stackoverflow