如何将下拉菜单更改为单选按钮?

时间:2013-11-12 11:49:51

标签: ruby-on-rails ruby button radio

我有一个下拉菜单,其中包含一系列选项:

select_tag(:"answers[#{question.question_no}]", options_for_select( [['Agree Strongly', 7], ['Agree Mostly', 6], ['Agree Somewhat', 5], ['Neither Agree Nor Disagree', 4], ['Disagree Somewhat', 3], ['Disagree Mostly', 2], ['Disagree Strongly', 1]] ))

我希望它能显示七个单选按钮。这怎么可能。如果有的话?

3 个答案:

答案 0 :(得分:3)

如果你想获得多个单选按钮,只需使用rails form helper:radio_button_tag

radio_button_tag(:"answers[#{question.question_no}]", '7')
label_tag(:answer_agree_strongly, "Agree Strongly")
radio_button_tag(:"answers[#{question.question_no}]", '6')
label_tag(:answer_agree_mostly, "Agree Mostly")
...

所有共享相同名称的单选按钮将被分组,用户只能选择一个。

P.S。可能你想迭代你的选项数组,以使代码更清晰。

答案 1 :(得分:2)

   <%- [['Agree Strongly', 7],
       ['Agree Mostly', 6],
       ['Agree Somewhat', 5],
       ['Neither Agree Nor   Disagree', 4],
       ['Disagree Somewhat', 3],
       ['Disagree Mostly', 2],
       ['Disagree Strongly', 1]].each do |button| %>
      <%= radio_button_tag :name, button.first, :value => button.last %>
    <% end %>

甚至更好地列出控制器

...控制器

  def some_action
  @choices = [['Agree Strongly', 7],
           ['Agree Mostly', 6],
           ['Agree Somewhat', 5],
           ['Neither Agree Nor   Disagree', 4],
           ['Disagree Somewhat', 3],
           ['Disagree Mostly', 2],
           ['Disagree Strongly', 1]]
  end

...视图

   <% @choices.each do |button| %>
     <%= radio_button_tag :name, button.first, :value => button.last %>
   <% end %>

答案 2 :(得分:1)

当然可以:)

<% ['Agree Strongly', ..., 'Disagree Strongly'].each do |option| %>
  <%= radio_button_tag(:name, option) %>
  <%= label_tag("name_#{option}") %>
<% end %>