Ruby-on-rails 删除由 SimpleForm 生成的选择字段的空白选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15143306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove a blank option of select field that was generated by SimpleForm
提问by Serge Vinogradoff
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.
Choices["Categories"] 只是键=> 值对的散列。
SimpleForm generates a select field with all needed options, but it also makes first option blank.
This blank option is present in all select fields that were generated by SimpleForm.
SimpleForm 生成一个包含所有需要选项的选择字段,但它也使第一个选项为空。
此空白选项存在于 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?
像: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.
我试图对该属性进行存在验证,希望 SimpleForm 能够检测到它,但它没有帮助。
回答by Dylan Markow
You can pass a include_blank: false, include_hidden: falseoption:
您可以传递一个include_blank: false, include_hidden: false选项:
= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"], include_blank: false, include_hidden: false
回答by Antonio Jha
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":
或者您可以在模型中自定义回调操作以删除数组参数中的任何空字符串,假设参数名为“types”:
before_validation :remove_empty_string
def remove_empty_string
types.reject! { |l| l.empty? }
end
回答by Soumitra Sarkar
To remove a blank field from select it is necessary to show the selected so add selected: 1Then 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})%>
要从选择中删除空白字段,必须显示所选内容,因此添加selected: 1然后将提示设置为任何类似prompt: "Please Select"的内容最终输出将是
<%= select("social_links",:option_id, Option.all.collect {|p| [ p.name, p.id ] },{ selected: 1 , prompt: "Please Select"}, { class: 'form-control' , required:true})%>

