simple_form 错误地呈现单选按钮 [英] simple_form renders radio buttons incorrectly

查看:41
本文介绍了simple_form 错误地呈现单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 simple_form 我呈现一些单选按钮以在注册页面上选择性别.

Using simple_form I render some radio buttons to select Gender on registration page.

代码:

        = f.input :gender,
              :collection => gender,
              :as => :radio_buttons,
              :item_wrapper_class => 'inline'

这给出了如下输出:

有没有办法让第一个单选按钮在男性后面,第二个单选按钮在女性后面?

Is there a way to make the first radio button be behind Male and the 2nd radio button behind Female?

推荐答案

下面是比我原来的更好的解决方案.

Here is a better solution than my original below.

来自代码:

#   form_for @user do |f|
#     f.collection_radio_buttons(
#       :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
#     ) do |b|
#       b.label { b.radio_button + b.text }
#     end
#   end

我认为这就是您要找的:

I think this is what you are looking for:

<%= f.collection_radio_buttons(
    :gender, [['Male', 'Male'], ['Male', 'Male']], :first, :last
  ) do |b|
    b.label { b.text + b.radio_button }
  end
%>

您甚至可以在其中添加其他帮助程序,例如 image_tag:

You can even add other helpers like image_tag in there too:

<%= f.collection_radio_buttons(
    :gender, [['Male', 'Male'], ['Male', 'Male']], :first, :last
  ) do |b|
    b.label { image_tag("#{b.text}.png") + b.radio_button }
  end
%>

这个解决方案不是一个普通的自定义组件.这个自定义组件继承自 CollectRadioButtonsInput 而不是普通的 CollectionInput 类.我修改了2个相关方法.

This solution is not a normal custom component. This custom compontent inherits from CollectRadioButtonsInput instead of the normal CollectionInput class. I modified the 2 relevant methods.

内部 app/inputs/radio_buttons_left_label_input.rb

class RadioButtonsLeftLabelInput < SimpleForm::Inputs::CollectionRadioButtonsInput
  def input
    label_method, value_method = detect_collection_methods

    @builder.send("collection_radio_buttons",
      attribute_name, collection, value_method, label_method,
      input_options, input_html_options, &collection_block_for_nested_boolean_style
    )
  end

  protected

  def build_nested_boolean_style_item_tag(collection_builder)
    collection_builder.text.html_safe + collection_builder.radio_button.html_safe
  end
end

可以这样使用

<%= form.input :gender,
  :as => :radio_buttons_left_label,
  :collection => %w[Female Male]
%>

这篇关于simple_form 错误地呈现单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆