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
form_with(model: @object) โ model-based form generation
Auto CSRF token insertion (security)
New object โ POST(create), existing โ PATCH(update) auto-determined
f.text_field :name โ sent as post[name] parameter
f.select :category_id โ dropdown generation
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