使用简单表单的单选按钮为输入和标签自定义 ID

Custom IDs for input and label using Simple Form's radio buttons

我正在为一页中的同一资源创建多个表单。这些表单中的每一个都有单选按钮。

但是,简单表单将相同的 ID 分配给所有表单中的相同单选按钮选项,从而导致冲突。

我如何命名每个表单,或者 select 每个标签和输入的自定义 ID?

如果您在视图中使用多个 simple_form_for 方法,它们只是 clever wrappers around the form_for built-in rails helper which supports the namespace option. Quoting from the form_for docs:

:namespace - A namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

所以,像下面这样的东西应该可以工作:

<%= simple_form_for @resource, namespace: "first_form" do |f| %>
...
<% end %>


<%= simple_form_for @resource, namespace: "second_form" do |f| %>
...
<% end %>