๐Ÿ“

Form Helpers

Safe and convenient form building with form_with

Rails Form Helpers provide security and convenience over plain HTML <form> tags.

<%= 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) auto-handles:

  • @post.new_record? โ†’ POST /posts (create)

  • @post.persisted? โ†’ PATCH /posts/1 (update)

  • Auto CSRF token insertion

  • Parameters: post[title], post[content] format

Key helpers:
text_field, text_area, password_field, email_field, number_field, date_field, select, check_box, radio_button, file_field, hidden_field

Key Points

1

form_with(model: @object) โ€” model-based form generation

2

Auto CSRF token insertion (security)

3

New object โ†’ POST(create), existing โ†’ PATCH(update) auto-determined

4

f.text_field :name โ€” sent as post[name] parameter

5

f.select :category_id โ€” dropdown generation

6

f.submit โ€” auto text "Create Post" or "Update Post"

Pros

  • Automatic CSRF protection
  • Auto HTTP method determination
  • Auto parameter naming conventions
  • Seamless integration with Strong Parameters

Cons

  • Helpers inconvenient when custom HTML is needed
  • Possible conflicts with JavaScript frameworks
  • Need to understand Turbo interaction
  • Complex nested forms are tricky to configure

Use Cases

CRUD form creation Search forms File upload forms Nested forms (accepts_nested_attributes_for)