Ruby-on-rails Rails - SimpleForm 中默认选中的单选按钮:collection

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6477942/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:27:50  来源:igfitidea点击:

Rails - Default selected radiobutton in SimpleForm :collection

ruby-on-railsruby-on-rails-3simple-form

提问by mswiszcz

I've litte problem with radiobuttons in SimpleForm.

我对 SimpleForm 中的单选按钮有一些小问题。

When i use

当我使用

= f.association :manufactureType, :collection => ManufactureType.all, :as => :radio

Rails simply generates few radiobuttons, but none of them are selected. I want first radiobutton to be selected by default. How can i make it?

Rails 只生成很少的单选按钮,但没有一个被选中。我希望默认选择第一个单选按钮。我怎样才能做到?

Thanks

谢谢

回答by Domness

If you pass in the manufacture types into the view, you can do the following:

如果您将制造类型传递到视图中,您可以执行以下操作:

:checked => @manufacture_types[0]

Or

或者

:checked => ManufactureType.first

回答by penner

My example was slightly more complicated, none of the other answers worked for me since there was no collection or model to reference.

我的例子稍微复杂一些,其他答案都不适合我,因为没有可供参考的集合或模型。

= f.input :attending, as: :radio_buttons, :collection => [ ['Yes', true], ['No', false] ], :checked => ['Yes', true]

回答by schpet

from op's comment, adding this parameter worked for me:

根据 op 的评论,添加此参数对我有用:

:checked => 1

回答by The Whiz of Oz

Here is an excerpt of my code which works:

这是我的代码的摘录:

= f.input :body_format,
  collection: [['markdown', 'Markdown']],
  label_method: :last,
  value_method: :first,
  as: :radio_buttons,
  checked: 'markdown', # THIS
  required: true