This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Rails Form Helpers Cheatsheet

A quick reference guide for Rails form helpers: form_with, model binding, input fields, selects, checkboxes, radio buttons, and CSRF protection.

· Published

Rails provides form_with to generate forms bound to ActiveRecord models with built-in CSRF token protection and RESTful route conventions.

Model-Bound Forms (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 %>

Common Input Helpers

Helper Generates 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">

Select Dropdowns

<!-- Collection select from ActiveRecord query -->
<%= f.collection_select :category_id, Category.all, :id, :name, prompt: "Select category" %>

<!-- Static select list -->
<%= f.select :role, [["Admin", "admin"], ["Member", "member"]], include_blank: true %>

Nested Attributes (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 %>

References

Related topics