code

Rails의 라디오 버튼

codestyles 2020. 12. 15. 19:20
반응형

Rails의 라디오 버튼


이 질문과 유사합니다 : 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>

또한 이전에 선택한 항목을 자동으로 확인할 수 있기를 원합니다 (이 양식이 다시로드 된 경우). 매개 변수를 기본값으로로드하려면 어떻게해야합니까?


마찬가지로 이 이전 게시물 약간의 트위스트와 함께 :

<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'}

관련 Railscast를 살펴보십시오.

업데이트 : 최근 에 formtastic과 유사한 구문을 가지고 있지만 더 가볍고 특히 스타일을 자신의 CSS에 남겨 두는 Simple Form 으로 이동했습니다 .


흠, 문서에서 라디오 버튼에 ID를 설정하는 방법을 알 수 없습니다. 속성에 대한 레이블은 라디오의 ID에 연결하려고합니다.

radio_button_tag에 대한 rails 문서

That said, from the doc, that first param is the "name"... which if that is what it is creating, should group them alltogether. If not, maybe its a bug?

Hmm, wonder if these have been fixed: http://dev.rubyonrails.org/ticket/2879 http://dev.rubyonrails.org/ticket/3353

ReferenceURL : https://stackoverflow.com/questions/623051/radio-buttons-on-rails

반응형