Rails 上的单选按钮

59

类似于这个问题:Rails上的复选框

在Ruby on Rails中,制作与某个问题相关的单选按钮的正确方法是什么?目前我有:

<div class="form_row">
    <label for="theme">Theme:</label>
    <br><%= radio_button_tag 'theme', 'plain', true %> Plain
    <br><%= radio_button_tag 'theme', 'desert' %> Desert
    <br><%= radio_button_tag 'theme', 'green' %> Green
    <br><%= radio_button_tag 'theme', 'corporate' %> Corporate
    <br><%= radio_button_tag 'theme', 'funky' %> Funky
</div>

我也想能够自动检查先前选择的项目(如果重新加载了此表单)。如何将参数加载到这些默认值中?

5个回答

76

就像之前的这个帖子所说的一样,只是有些微小的变化:

<div class="form_row">
    <label for="theme">Theme:</label>
    <% [ 'plain', 'desert', 'green', 'corporate', 'funky' ].each do |theme| %>
      <br><%= radio_button_tag 'theme', theme, @theme == theme %>
      <%= theme.humanize %>
    <% end %>
</div>

在哪里

@theme = params[:theme]

3
可以将[ 'plain', 'desert', 'green', 'corporate', 'funky' ]简化为%w(plain desert green corporate funky) - gabe

41

与 V 的相同,但每个单选按钮都有相关的标签。点击标签将选中单选按钮。

<div class="form_row">
  <p>Theme:</p>
  <% [ 'plain', 'desert', 'green', 'corporate', 'funky' ].each do |theme| %>
    <br><%= radio_button_tag 'theme', theme, @theme == theme %>
    <%= label_tag "theme_#{theme}", theme.humanize %>
  <% end %>
</div>

使用 label_tag 可以帮助改善用户体验 :) - abhishek77in

8

使用 Haml,消除不必要的 br 标签,并将输入框嵌套在标签内,以便可以在不匹配标签和 ID 的情况下选择它们。同时使用 form_for。我认为这是遵循最佳实践的做法。

= form_for current_user do |form|
  .form_row
    %label Theme:
    - [ 'plain', 'desert', 'green', 'corporate', 'funky' ].each do |theme|
      %label
        = form.radio_button(:theme, theme)
        = theme.humanize

4
我建议您查看formtastic,它可以使单选按钮和复选框集合的处理更加简便和简洁。您的代码将如下所示:
    <% semantic_form_for @widget, :html => {:class => 'my_style'} do |f| %>
<%= f.input :theme, :as => :radio, :label => "Theme:", 
:collection =>  [ 'plain', 'desert', 'green', 'corporate', 'funky' ] %>
<% end %>

Formtastic是一种不会过多干扰的表单构建工具,可以与“经典”表单构建器混合使用。您还可以覆盖表单的formtastic CSS类,就像我上面所做的那样,使用
:html => {:class => 'my_style'}

请查看相关的Railscasts。

更新:我最近转向使用Simple Form,它具有与formtastic类似的语法,但更加轻量级,特别是将样式留给您自己的CSS。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接