【问题标题】:Radio buttons on RailsRails 上的单选按钮
【发布时间】:2010-10-12 00:06:08
【问题描述】:

类似这个问题:Checkboxes on 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>

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

【问题讨论】:

    标签: ruby-on-rails ruby webforms radio-button


    【解决方案1】:

    this previous post 一样,略有不同:

    <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]
    

    【讨论】:

    • 您可以将[ 'plain', 'desert', 'green', 'corporate', 'funky' ] 简化为%w(plain desert green corporate funky)
    【解决方案2】:

    与 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 有助于改善用户体验:)
    【解决方案3】:

    使用 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 在很大程度上不引人注目,可以与“经典”表单构建器混合和匹配。您还可以像我在上面所做的那样,使用
      :html =&gt; {:class =&gt; 'my_style'}

      覆盖表单的 formtastic css 类

      看看相关的 Railscasts。

      更新:我最近搬到了Simple Form,它的语法与 formtastic 相似,但更轻量级,尤其是留给您自己的 css 样式。

      【讨论】:

        【解决方案5】:

        嗯,从文档中我看不到如何在单选按钮上设置 ID...标签的 for 属性试图链接到单选按钮上的 ID。

        rails docs for radio_button_tag

        也就是说,从文档中,第一个参数是“名称”......如果这是它正在创建的内容,应该将它们组合在一起。如果不是,那可能是一个错误?

        嗯,想知道这些是否已修复: http://dev.rubyonrails.org/ticket/2879 http://dev.rubyonrails.org/ticket/3353

        【讨论】:

          猜你喜欢
          • 2017-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-05
          相关资源
          最近更新 更多