📝

Form Helpers

form_with로 안전하고 편리한 폼 작성

Rails의 Form Helper는 단순 HTML <form> 태그 대신 보안과 편의성을 제공합니다.

<%= form_with(model: @post) do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title, class: 'input' %>

  <%= f.label :content %>
  <%= f.text_area :content, rows: 10 %>

  <%= f.label :category_id %>
  <%= f.select :category_id, Category.pluck(:name, :id) %>

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

form_with(model: @post)의 자동 처리:

  • @post.new_record? → POST /posts (create)

  • @post.persisted? → PATCH /posts/1 (update)

  • CSRF 토큰 자동 삽입

  • 파라미터: post[title], post[content] 형태

주요 헬퍼:
text_field, text_area, password_field, email_field, number_field, date_field, select, check_box, radio_button, file_field, hidden_field

핵심 포인트

1

form_with(model: @object) — 모델 기반 폼 생성

2

자동 CSRF 토큰 삽입 (보안)

3

새 객체 → POST(create), 기존 객체 → PATCH(update) 자동 결정

4

f.text_field :name — post[name] 파라미터로 전송

5

f.select :category_id — 드롭다운 생성

6

f.submit — "Create Post" 또는 "Update Post" 자동 텍스트

장점

  • CSRF 보호 자동
  • HTTP 메서드 자동 결정
  • 파라미터 네이밍 규약 자동 적용
  • Strong Parameters와 자연스럽게 연동

단점

  • 커스텀 HTML이 필요할 때 헬퍼가 오히려 불편
  • JavaScript 프레임워크와 충돌 가능
  • Turbo와의 상호작용 이해 필요
  • 복잡한 중첩 폼은 설정이 까다로움

사용 사례

CRUD 폼 생성 검색 폼 파일 업로드 폼 중첩 폼 (accepts_nested_attributes_for)