빠른 참조

Rails 폼 헬퍼 치트시트

Rails 폼 헬퍼 빠른 참조 가이드: form_with, 모델 바인딩, 입력 필드, 드롭다운 셀렉트, 체크박스 및 CSRF 보호.

· 게시일

Rails는 내장 CSRF 토큰 보호와 RESTful 라우팅 규칙을 갖춘 ActiveRecord 모델 바인딩 폼을 생성할 수 있는 form_with를 제공합니다.

모델 바인딩 폼 (form_with)

<%= form_with model: @user do |f| %>
  <% if @user.errors.any? %>
    <div class="errors">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited saving:</h2>
      <ul>
        <% @user.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.label :name, "Full Name" %>
  <%= f.text_field :name, class: "input-field" %>

  <%= f.label :email %>
  <%= f.email_field :email %>

  <%= f.label :password %>
  <%= f.password_field :password %>

  <%= f.submit "Create Account", class: "btn-primary" %>
<% end %>

주요 입력 헬퍼

헬퍼 생성되는 HTML
f.text_field :title <input type="text">
f.email_field :email <input type="email">
f.number_field :age <input type="number">
f.date_field :born_on <input type="date">
f.text_area :bio <textarea>
f.check_box :active <input type="checkbox">
f.radio_button :role, "admin" <input type="radio">
f.file_field :avatar <input type="file">
f.hidden_field :token <input type="hidden">

드롭다운 셀렉트

<!-- ActiveRecord 쿼리 기반 컬렉션 셀렉트 -->
<%= f.collection_select :category_id, Category.all, :id, :name, prompt: "Select category" %>

<!-- 정적 셀렉트 목록 -->
<%= f.select :role, [["Admin", "admin"], ["Member", "member"]], include_blank: true %>

중첩 속성 (fields_for)

<%= form_with model: @author do |f| %>
  <%= f.text_field :name %>

  <%= f.fields_for :profile do |profile_fields| %>
    <%= profile_fields.text_field :twitter_handle %>
    <%= profile_fields.text_area :bio %>
  <% end %>

  <%= f.submit %>
<% end %>

참고 자료

관련 주제