表单上的单选按钮在表单验证失败后无法正确呈现 - 引导程序

dmt*_*989 4 html ruby-on-rails radio-button twitter-bootstrap

带有Bootstrap 3的Rails 4应用程序

我有一个包含单选按钮输入的表单:

<strong> Radio button options on form </strong><br>
   <div class="form-group">
     &nbsp<%= f.radio_button :category, 'A' %> &nbsp <%= f.label "A", "A" %><br /> 
     &nbsp<%= f.radio_button :category, 'B' %> &nbsp <%= f.label "B", "B" %><br />  
     &nbsp<%= f.radio_button :category, 'C' %> &nbsp <%= f.label "C", "C" %><br />
   </div>
Run Code Online (Sandbox Code Playgroud)

第一次加载表单时,一切看起来都正确:

在此输入图像描述

我的问题是,如果表单由于验证错误而失败(缺少所需的输入等,在表单上的任何位置),当页面重新呈现时,单选按钮和标签显示在两个不同的行上:

在此输入图像描述

我该如何解决这个问题?

更新 为每个生成的HTML是:原始(正确):

    <strong> Radio button options on form </strong><br>
    <div class="form-group">
      &nbsp<input id="listing_category_1" name="listing[category]" type="radio" value="1" /> &nbsp <label for="listing_1">A</label><br /> 
      &nbsp<input id="listing_category_2" name="listing[category]" type="radio" value="2" /> &nbsp <label for="listing_2">B</label><br />  
      &nbsp<input id="listing_category_3" name="listing[category]" type="radio" value="3" /> &nbsp <label for="listing_3">C</label><br />
    </div>
Run Code Online (Sandbox Code Playgroud)

并且为了重新渲染(不正确):

    <strong> Radio button options on form </strong><br>
    <div class="form-group">
      &nbsp<div class="field_with_errors"><input id="listing_category_1" name="listing[category]" type="radio" value="1" /></div> &nbsp <label for="listing_1">A</label><br /> 
      &nbsp<div class="field_with_errors"><input id="listing_category_2" name="listing[category]" type="radio" value="2" /></div> &nbsp <label for="listing_2">B</label><br />  
      &nbsp<div class="field_with_errors"><input id="listing_category_3" name="listing[category]" type="radio" value="3" /></div> &nbsp <label for="listing_3">C</label><br />
    </div>
Run Code Online (Sandbox Code Playgroud)

mar*_*ets 8

这是因为Rails将包含错误的字段包含在div:

<div class="field_with_errors">
  <input name="foo" type="radio" value="1" />
</div>
Run Code Online (Sandbox Code Playgroud)

一种解决方法可以是自定义此类css,例如制作div显示属性inline而不是block:

.field_with_errors { display: inline; }
Run Code Online (Sandbox Code Playgroud)

另一个选项,修改Rails设置以在显示错误时更改默认行为:

config.action_view.field_error_proc = Proc.new { |html_tag, instance| "<span class='field_with_errors'>#{html_tag}</span>".html_safe }
Run Code Online (Sandbox Code Playgroud)

  • 添加 .field_with_errors { display: inline; CSS 的作用就像一个魅力。谢谢! (2认同)