Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Forms, Validation and Callbacks

Forms with form_with

Build Rails forms with form_with, model-backed fields, labels, selects, checkboxes, nested attributes and file uploads. Understand the HTML it generates, the CSRF token and the hidden method field.

Forms are how users send data to your app: sign up, write a post, check out. In plain HTML you must write every <input> name correctly, remember the right HTTP method, protect against forged requests and refill the fields when something goes wrong. Rails' form_with helper does all of that from one line: give it a model and it picks the URL, the method, the field names and the security token.

This lesson shows form_with for models and for plain URLs, the field helpers, and the HTML that comes out. Rails cannot run here, so the ERB is read-only, and the runnable stand-in is a small Ruby form builder that produces similar HTML so you can see the mechanism. Handling the submitted data is the topic of the next lesson, strong parameters.

A form for a model

ERB
<%= form_with model: @post do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :body %>
    <%= form.text_area :body, rows: 8 %>
  </div>
  <%= form.submit %>
<% end %>

If @post is a new record (Post.new), Rails builds a form that does POST /posts. If it is an existing record, the same code builds PATCH /posts/7. The submit button says "Create Post" or "Update Post" automatically. That is why Rails apps usually keep one _form.html.erb partial and render it from both new and edit.

The generated HTML looks roughly like this:

HTML
<form action="/posts" accept-charset="UTF-8" method="post">
  <input type="hidden" name="authenticity_token" value="...long random token...">
  <div>
    <label for="post_title">Title</label>
    <input type="text" name="post[title]" id="post_title">
  </div>
  <div>
    <label for="post_body">Body</label>
    <textarea rows="8" name="post[body]" id="post_body"></textarea>
  </div>
  <input type="submit" name="commit" value="Create Post" data-disable-with="Create Post">
</form>

Three details matter:

  1. Field names are namespaced: post[title]. Rack turns that into a nested hash { "post" => { "title" => "..." } }, which params[:post] reads.
  2. authenticity_token is the CSRF token. Rails refuses a non-GET request without a valid one (see web security).
  3. PATCH and DELETE are not real browser form methods. For an existing record Rails emits method="post" plus a hidden <input name="_method" value="patch">, and the Rack middleware converts it back.
Ruby Stand-in: a tiny form builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Look at the second form: the quotes, ampersand and angle brackets in the title were escaped. Rails does that for every value, which is part of why server-rendered forms are safe by default.

Field helpers

Helper HTML
text_field, email_field, password_field, number_field, url_field, telephone_field <input type="...">
text_area <textarea>
check_box a hidden 0 plus a checkbox 1 (so unchecked still submits)
radio_button :status, "draft" radio input
select :category_id, Category.pluck(:name, :id) <select> with options
collection_select, collection_radio_buttons, collection_check_boxes choices from a collection
date_field, datetime_local_field, time_field HTML5 date inputs
file_field :avatar file upload (form becomes multipart/form-data)
hidden_field hidden input
submit, button buttons

Rails fills each field with the current value of the model attribute, so after a failed save the user sees what they typed. Pass any HTML attribute as an option: form.text_field :title, class: "input", placeholder: "Title", required: true, autofocus: true.

form_with for a URL, not a model

For a search box or login form with no model, give a URL and optionally a scope:

ERB
<%= form_with url: search_path, method: :get do |form| %>
  <%= form.search_field :q, placeholder: "Search" %>
  <%= form.submit "Go" %>
<% end %>

Without scope:, the names are plain (q, not search[q]). GET forms do not include the CSRF token.

A select that sets a foreign key:

ERB
<%= form.collection_select :author_id, User.order(:name), :id, :name, prompt: "Choose" %>

A group of checkboxes for a many-to-many link:

ERB
<%= form.collection_check_boxes :tag_ids, Tag.order(:name), :id, :name %>

Because the param is tag_ids (an array), assigning it updates the join records: Rails creates and removes them for you. This works with a has_many :through.

To edit children in the same form, use nested attributes:

Ruby
class Order < ApplicationRecord
  has_many :line_items, dependent: :destroy
  accepts_nested_attributes_for :line_items, allow_destroy: true, reject_if: :all_blank
end
ERB
<%= form.fields_for :line_items do |item| %>
  <%= item.text_field :name %>
  <%= item.number_field :quantity %>
<% end %>

Remember to permit line_items_attributes in the controller. Nested forms are powerful but easy to overuse; for complex multi-model screens, a form object is often clearer.

File uploads

ERB
<%= form_with model: @user do |form| %>
  <%= form.file_field :avatar, accept: "image/*" %>
<% end %>

With Active Storage, the model declares has_one_attached :avatar and Rails stores the file (on disk, S3, etc.) outside your database. Validate size and content type yourself; the accept attribute is only a hint for the browser.

Turbo and submissions

Rails 7+ apps ship with Turbo. Forms submit through fetch automatically, and the server answers with a redirect on success or a rendered form on failure. For failures, return a status of 422 Unprocessable Content: Turbo only re-renders the form when it sees an error status.

Ruby
def create
  @post = Post.new(post_params)
  if @post.save
    redirect_to @post, notice: "Saved"
  else
    render :new, status: :unprocessable_entity
  end
end

Do not build forms with raw <form> tags and hand-typed field names unless you must. You lose the CSRF token, escaping and the model-aware behavior. If you do write a raw form, add <%= hidden_field_tag :authenticity_token, form_authenticity_token %>.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does form_with model: @post decide between POST /posts and PATCH /posts/7?

    A new record gives POST to the collection path; a persisted record gives PATCH to the member path.
  2. 2. What name does form.text_field :title produce inside a form for a Post?

    Rails namespaces fields as model[attribute], which Rack parses into a nested hash.
  3. 3. Why does check_box also emit a hidden input?

    Browsers omit unchecked boxes; the hidden 0 makes the attribute present as false.
  4. 4. What status should render :new use after a failed save so Turbo re-renders the form?

    Turbo only swaps in a rendered response to a form submit when it has an error status such as 422.

Summary

  • form_with model: picks URL, method, field names and submit text from the record.
  • Fields are named model[attribute] and refilled from the model.
  • Rails adds the CSRF token and a hidden _method for PATCH and DELETE.
  • Use form_with url: for search and login forms without a model.
  • Selects, checkbox groups and nested attributes edit associations.
  • Render failed forms with status 422 so Turbo displays them.

Next: Strong parameters