多个单选按钮组,以数组形式发送数据

Tom*_*mmy 2 ruby-on-rails

我尝试过以下方法:

<%= form_for .... do |f| %>
    <%= f.label "test1" %>
        <%= radio_button_tag 'value[]', "1" %>
        <%= radio_button_tag 'value[]', "2" %>
    <%= f.label "test2" %>
        <%= radio_button_tag "value[]", "1" %>
        <%= radio_button_tag "value[]", "2" %>
    <%= f.submit "test_send" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我有一个数组.

现在的问题是我只能选择这四个中的一个,但我希望在组后选择它们.随着text_fields它工作正常,但与单选按钮不起作用.

然后我尝试了类似的东西:

<%= form_for .... do |f| %>
    <%= f.label "test1" %>
        <%= radio_button_tag 'value[]', "1", :id => "btn-grp-1"  %>
        <%= radio_button_tag 'value[]', "2", :id => "btn-grp-2"  %>
    <%= f.label "test2" %>
        <%= radio_button_tag "value[]", "1", :id => "btn-grp-3"  %>
        <%= radio_button_tag "value[]", "2", :id => "btn-grp-4"  %>
    <%= f.submit "test_send" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

有唯一的ID,但仍然是同样的问题.我需要的是为每个组都有一个唯一的名称,如:

<%= form_for .... do |f| %>
    <%= f.label "test1" %>
        <%= radio_button_tag 'value[1]', "1", :id => "btn-grp-1"  %>
        <%= radio_button_tag 'value[1]', "2", :id => "btn-grp-2"  %>
    <%= f.label "test2" %>
        <%= radio_button_tag "value[2]", "1", :id => "btn-grp-3"  %>
        <%= radio_button_tag "value[2]", "2", :id => "btn-grp-4"  %>
    <%= f.submit "test_send" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

但是我现在如何获得参数?

我的控制器包含用于测试发送内容的ony代码:

...
def create

    flash[:success] = valueset_params[:value]
    redirect_to root_path
end


private

def valueset_params
  params.permit({value: []})
end
...
Run Code Online (Sandbox Code Playgroud)

希望你明白我的意思.(我必须更改单选按钮的名称,我仍然希望在我的控制器中接收完整的数组).

只要问你是不是.

感谢您提出任何解决方案.


编辑另一个问题:

我有类似的@topics地方,里面有多个主题.现在我想循环它们(我知道它是如何工作的)并在[]中写入变量值

<%= form_for .... do |f| %>
  <%= f.label 'test1' %>
    <%= radio_button_tag 'value[@topic1.id]', '1' %>
    <%= radio_button_tag 'value[@topic1.id]', '2' %>
  <%= f.label 'test2' %>
    <%= radio_button_tag 'value[@topic2.id]', '1' %>
    <%= radio_button_tag 'value[@topic2.id]', '2' %>
  <%= f.submit 'test_send' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

Rai*_*dal 7

试试这个,让我知道会发生什么:

<%= form_for .... do |f| %>
  <%= f.label 'test1' %>
    <%= radio_button_tag 'value[group_one]', '1' %>
    <%= radio_button_tag 'value[group_one]', '2' %>
  <%= f.label 'test2' %>
    <%= radio_button_tag 'value[group_two]', '1' %>
    <%= radio_button_tag 'value[group_two]', '2' %>
  <%= f.submit 'test_send' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

您应该能够在控制器中获取数据params[:value],然后使用params[:value][:group_one]params[:value][:group_two].

  • 对于你的第二个问题,只需使用``value [#{topic.id}]"`和周围的循环`@topics.each do | topic | ......结束 (2认同)