레일의 라디오 버튼
-
05-07-2019 - |
문제
이 질문과 유사 : 레일의 확인란
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 => {:class => 'my_style'}
관련 레일 스 캐스트를 살펴보십시오.
업데이트 : 최근에 이사했습니다 간단한 양식 이는 형태와 비슷한 구문을 가지고 있지만 더 가벼우 며 특히 스타일링을 자신의 CSS로 남겨 둡니다.
흠, 문서에서 라디오 버튼에서 ID를 설정하는 방법을 알지 못합니다 ... 속성의 레이블은 라디오에서 ID에 링크하려고합니다.
즉, 문서에서 첫 번째 매개 변수는 "이름"입니다. ~해야 한다 그것들을 alltogether로 그룹화하십시오. 그렇지 않다면 아마도 버그일까요?
흠, 고정되었는지 궁금합니다.http://dev.rubyonrails.org/ticket/2879 http://dev.rubyonrails.org/ticket/3353