Rails上的单选按钮
-
05-07-2019 - |
题
与此问题类似: 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>
我还希望能够自动检查以前选择的项目(如果重新加载此表单)。如何将参数加载到这些的默认值?
解决方案
与上一篇文章一样,略有改动:
<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]
其他提示
与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>
使用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
我建议您查看 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 =&gt; {:class =&gt; 'my_style'} 代码>
查看相关的Railscast。
更新:我最近转到简单表单,其语法类似于formtastic但更轻巧,特别是给你自己的css留下了造型。
嗯,从文档中我看不出如何在单选按钮上设置ID ...属性的标签试图链接到收音机上的ID。
也就是说,从文档开始,第一个参数就是“名称”...如果它正在创建,那么应该将它们全部分组。如果没有,也许它是一个错误?
嗯,不知道这些是否已修复: http://dev.rubyonrails.org/ticket/2879 http://dev.rubyonrails.org/ticket/3353不隶属于 StackOverflow