rails 4 radio_button_tag 默认不选

rails 4 radio_button_tag default not selected

我正在使用 Rails 4,但无法使用 radio_button_tag 将第一个选项设置为默认值。

.field
  =radio_button_tag :type, "order", checked:"true", class: "rfi_radio"
  =label_tag :type_order, "Information pertaining to an order"
  br
  =radio_button_tag :type, "quote", class: "rfi_radio"
  =label_tag :type_quote, "Information pertaining to a quote"
  br
  =radio_button_tag :type, "customer", class: "rfi_radio"
  =label_tag :type_customer, "Information pertaining to a customer"
  br
  =radio_button_tag :type, "general", class: "rfi_radio"
  =label_tag :type_general, "General information"

看看doc for the radio_button_tag

这应该有效:

.field
    =radio_button_tag :type, "order", true, class: "rfi_radio"

根据 http://apidock.com/rails/ActionView/Helpers/FormTagHelper/radio_button_tag,您应该只传递布尔值而不是散列值。

=radio_button_tag :type, "order", true, class: "rfi_radio"

Rails 将默认单选按钮设置为默认选中。在它正常工作之前,我必须将所有替代项设置为 false。

.field
  =radio_button_tag "type", "order", true,  class: "rfi_radio"
  =label_tag :type_order, "Information pertaining to an order"
  br
  =radio_button_tag "type", "quote", false, class: "rfi_radio"
  =label_tag :type_quote, "Information pertaining to a quote"
  br
  =radio_button_tag "type", "customer", false, class: "rfi_radio"
  =label_tag :type_customer, "Information pertaining to a customer"
  br
  =radio_button_tag "type", "general", false, class: "rfi_radio"
  =label_tag :type_general, "General information"

我刚花了一个小时弄清楚这个问题,所以想分享一下,以防对其他人有帮助:

  • radio_button_tag's checked parameter will show the radio button as checked no matter what it's provided as the argument (unless nil or false) since most everything else is "truthy".
  • 我必须向 提供 checked 参数,正好是一组中的一个 单选按钮(组是那些单选按钮同名按钮)。

希望这些提示对您有所帮助!