Rails 5 simple_form 根据需要标记单选按钮,如果未填写则阻止提交表单

Rails 5 simple_form mark radio button as required & prevent form submit if not filled

我想根据需要在我的表单中标记一个单选按钮字段,这样如果用户单击提交(没有选择单选按钮选项),他将得到一个错误,指出这个字段是必需的,就像正常情况下发生的一样输入字段(当具有如图所示的选项 required: true 时)

例如:(这个效果很好)

= f.input :value, required: true

但这行不通:

= f.collection_radio_buttons :some_symbol, [[true, t('yes')], [false, t('no')]], :first, :last, required: true

我正在使用 Rails 5.2,simple_form & jQuery,虽然我确信这个用例面对许多开发人员,但我找不到相关的 question/answer 除了javascript hacks(我更愿意避免并且更喜欢使用 Rails 或 simple_form 方式来强制执行此前端验证)

检查方法的签名https://apidock.com/rails/v6.0.0/ActionView/Helpers/FormOptionsHelper/collection_radio_buttons

collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)

您有一个 options 散列,然后是一个 html_options 散列。您对该方法的调用是将 required: true 设置为一个选项,我认为您需要将其设置为 html_option。在:lastrequired: true之间添加一个空的{}

= f.collection_radio_buttons :some_symbol, [[true, t('yes')], [false, t('no')]], :first, :last, {}, required: true