Skip to main content
April 1, 2026Noble Desktop Publishing Team/9 min read

Forms in Rails: Creating a Form

Master Rails Forms with Model Integration and Advanced Components

Core Rails Form Components

Form_with Helper

The modern Rails approach to building forms with automatic model binding and CSRF protection built-in.

Form Builder Object

Intelligent object that knows your model structure and generates appropriate HTML with proper naming conventions.

Security Features

Automatic authenticity tokens and cross-site request forgery protection without additional configuration.

Topics Covered in This Ruby on Rails Tutorial:

Form_with, Checkboxes, Radio Buttons, & Select Boxes, Adding a Dropdown Menu, Adding a Date Selector & Submit Button

Exercise Preview

preview rails forms

Exercise Overview

In this exercise, we'll master one of Rails' most powerful features: forms for updating models. Forms represent the critical junction where controllers, views, and model objects converge to create dynamic, data-driven applications. While HTML forms can be complex and error-prone when built manually, Rails transforms form creation into an elegant, secure process—and as you'll discover, forms tied to model objects (like our movies model) become remarkably intuitive.

Understanding Rails forms is essential for any serious web developer. Modern web applications demand sophisticated user interfaces that can handle complex data relationships, validation, and security concerns seamlessly. By the end of this exercise, you'll have the expertise to build production-ready forms that leverage Rails' built-in protections and conventions.

  1. If you completed the previous exercises, you can skip the following sidebar. We strongly recommend completing the previous exercises before proceeding, as they establish the foundational knowledge and project structure you'll need. If you haven't finished them, follow the setup instructions in the sidebar below.

If You Did Not Do the Previous Exercises (3A–3D)

  1. Close any files you may have open.
  2. Open the Finder and navigate to Class Files > yourname-Rails Class
  3. Open Terminal.
  4. Type cd and a single space (do NOT press Return yet).
  5. Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
  6. Run rm -rf flix to delete your copy of the Flix site.
  7. Run Git clone https://bitbucket.org/Noble Desktop/flix.Git to copy the Flix Git repository.
  8. Type cd flix to enter the new directory.
  9. Type Git checkout 3D to bring the site up to the end of the previous exercise.
  10. Run bundle to install any necessary gems.
  11. Run yarn install—check-files to install JavaScript dependencies.

Getting Started

Before diving into form creation, we need to establish the proper MVC architecture. We'll start by creating a controller action that will serve our form view, then build the corresponding template. This approach follows Rails conventions and ensures our form has the proper data context it needs to function.

  1. Open the Finder and navigate to Class Files > yourname-Rails Class

  2. Open Terminal.

  3. Type cd and a single space (do NOT press Return yet).

  4. Drag the flix folder from the Finder to the Terminal window.

  5. Make sure you're in Terminal and hit Return to change into the new folder.

  6. Type the following to launch the server:

    rails server
  7. Open a browser and navigate to localhost:3000 to verify everything is running correctly. You should see the Flix website load without errors.

  8. In your code editor, open flix > app > controllers > movies_controller.rb

    Pro tip: Open the entire flix folder in your code editor for easier navigation between files—most modern editors like VS Code, Sublime Text, and Atom support this workflow.

  9. Scroll to the bottom and before the final end add the following code:

    def new
          @movie = Movie.new
       end
    end

    This new action creates a fresh Movie instance that our form will use. The @movie instance variable will be accessible in our view template, providing the form builder with the context it needs to generate proper field names, validation handling, and data binding.

  10. Save the file.

  11. Create a new file in your code editor for our view template.

  12. Type the following on the very first line:

    <h1>Add Movie</h1>
  13. Save the file:
    • Into yourname-Rails Class > flix > app > views > movies
    • Name it new.html.erb

Setting Up Your Development Environment

1

Navigate to Project Directory

Use Terminal to cd into your Rails project folder and ensure all dependencies are properly installed

2

Launch Rails Server

Run 'rails server' command and verify the application loads correctly at localhost:3000

3

Create Controller Action

Add the 'new' action to your movies controller to handle form display and model instantiation

Form_with Model

Now we'll implement Rails' modern form_with helper, which represents the current best practice for form creation in Rails applications. This helper automatically handles CSRF protection, proper HTTP methods, and generates clean, semantic HTML. Unlike older form helpers, form_with provides a unified interface for both model-based and custom forms while maintaining Rails' security standards.

  1. In your new.html.erb file, add the following code:

    <h1>Add Movie</h1>
    <%= form_with model: @movie do |f| %>
    
    <% end %>

    This code establishes our form foundation. The form_with helper creates a form builder object (represented by |f|) that understands our Movie model's structure, attributes, and validation rules. This intelligent form builder will generate appropriate HTML elements, handle data binding, and ensure proper form submission routing.

  2. Add the title field by inserting this code between the form tags:

    <%= form_with model: @movie do |f| %>
       <p>
          <%= f.label :title %>
          <%= f.text_field :title %>
       </p>
    <% end %>

    The form builder automatically generates proper HTML attributes, including name, id, and accessibility features based on the model attribute.

  3. Save the file.

  4. Switch to Chrome and navigate to localhost:3000/movies/new to see your form in action.

  5. Right-click inside the input field and select Inspect to examine the generated HTML code. The Developer Tools reveal exactly how Rails transforms your simple ERB code into production-ready HTML.

    Notice that Rails automatically generated a complete form structure:

    <form action="/movies" accept-charset="UTF-8" data-remote="true" method="post">

    This includes proper encoding, RESTful routing, and modern JavaScript handling.

  6. Observe the hidden authenticity_token field in the generated HTML. This is Rails' built-in CSRF (Cross-Site Request Forgery) protection—a critical security feature that validates form submissions came from your application. This token is automatically generated and validated by Rails, providing enterprise-level security without additional configuration.

    The label and input elements also demonstrate Rails' attention to accessibility and semantic HTML:

    <label for="movie_title">Title</label>
    <input type="text" name="movie[title]" id="movie_title">
  7. Let's expand our form with a description field. Add this code after the title field:

    <%= f.text_field :title %>
       </p>
       <p>
          <%= f.label :description %>
          <%= f.text_area :description %>
       </p>
    <% end %>

    Note Rails' consistent naming convention: multi-word HTML elements like <textarea> become text_area in Rails helpers, following Ruby's underscore convention.

  8. Save and reload the page in Chrome.

  9. The description field appears but looks cramped. Rails form helpers accept HTML attributes as parameters, allowing precise control over the generated elements.

  10. Enhance the textarea with proper dimensions:

    <%= f.text_area :description, cols: 60, rows: 10 %>
  11. Save and reload to see the improved textarea size—now properly sized for meaningful content input.

Rails Auto-Generated Form Elements

Rails automatically creates form tags with proper action attributes, CSRF tokens, and semantic HTML structure. The form builder generates IDs like 'movie_title' for CSS styling and accessibility.

This is another important reason to always use form_with when constructing forms in Rails
The automatic security features and proper HTML generation make form_with essential for Rails development

Checkboxes, Radio Buttons, & Select Boxes

Modern web applications require sophisticated input controls beyond basic text fields. Rails provides elegant helpers for checkboxes, radio buttons, and select menus that automatically handle data binding, validation states, and accessibility requirements. These form controls are essential for creating professional user interfaces that guide users through complex data entry workflows.

  1. Add a checkbox for the subtitles field—perfect for boolean (true/false) values:

    <%= f.text_area :description, cols: 60, rows: 10 %>
       </p>
       <p>
          <%= f.label :has_subtitles %>
          <%= f.check_box :has_subtitles %>
       </p>
  2. Save and test the checkbox functionality. Notice that clicking the label text toggles the checkbox—this is proper accessibility implementation that Rails handles automatically.

  3. Now let's implement radio buttons for the placement field, which represents mutually exclusive options (In Theaters, Coming Soon, Go Now):

    <%= f.check_box :has_subtitles %>
       </p>
       <p>
          <%= f.label :placement %>
          <%= f.radio_button :placement, 'in_theaters' %>
       </p>

    Radio button syntax requires both the field name (:placement) and the specific value ('in_theaters'). The value is a string, not a symbol, as it represents data that will be stored in the database.

  4. Complete the radio button group:

    <%= f.label :placement %>
       <%= f.radio_button :placement, 'in_theaters' %>
       <%= f.radio_button :placement, 'coming_soon' %>
       <%= f.radio_button :placement, 'go_now' %>
  5. The radio buttons work but lack proper labels. Let's add accessible labels using Rails' label helper:

    <%= f.label :placement %>
          <%= f.radio_button :placement, 'in_theaters' %>
          <%= f.label :placement_in_theaters %>
          <%= f.radio_button :placement, 'coming_soon' %>
          <%= f.label :placement_coming_soon %>
          <%= f.radio_button :placement, 'go_now' %>
          <%= f.label :placement_go_now %>

    Rails automatically associates these labels with their corresponding radio buttons for proper accessibility.

  6. Test the labels—they should properly activate their radio buttons when clicked. Now let's customize the label text to be more user-friendly:

    <%= f.label :placement_in_theaters, "In Theaters" %>
    <%= f.radio_button :placement, 'coming_soon' %>
    <%= f.label :placement_coming_soon, "Coming Soon" %>
    <%= f.radio_button :placement, 'go_now' %>
    <%= f.label :placement_go_now, "Go Now" %>

    The second parameter overrides the default label text, giving us clean, professional labels while maintaining proper HTML associations.

Form Input Types for Different Data

FeatureInput TypeBest Use Case
CheckboxBoolean fieldsYes/No values like has_subtitles
Radio ButtonSingle choice from few optionsCategories like placement (3 options)
Select DropdownSingle choice from many optionsMPAA ratings with multiple values
Recommended: Choose radio buttons for 2-5 options, dropdowns for 6+ options, checkboxes for boolean values
Proper Label Association

Use f.label helper with specific field identifiers like 'placement_in_theaters' to ensure labels are clickable and improve user experience. Avoid plain text labels.

Adding a Dropdown Menu to the Form

Select dropdowns are ideal when users need to choose from a predefined list of options. For MPAA ratings, a dropdown provides a clean interface that prevents invalid entries while conserving screen space. Rails' select helpers offer powerful features for option generation, default values, and integration with both static lists and database records.

  1. Add the basic select structure for MPAA ratings:

    <%= f.label :placement_go_now, "Go Now" %>
       </p>
       <p>
          <%= f.label :mpaa_rating %>
          <%= f.select :mpaa_rating %>
       </p>
  2. Save and reload—Rails will display an error because select elements require option definitions. This error handling helps catch configuration issues early in development.

  3. Define the rating options using Rails' options_for_select helper:

    <p>
       <% mpaa_ratings = options_for_select ["G", "PG", "R", "NR"] %>
       <%= f.label :mpaa_rating %>
       <%= f.select :mpaa_rating, mpaa_ratings %>
    </p>

    Note the absence of the equals sign in the first ERB tag—we're creating a variable, not outputting content to the HTML.

  4. The dropdown now works, but defaults to "G". For better user experience, let's require an explicit choice:

    <%= f.select :mpaa_rating, mpaa_ratings, include_blank: true %>

    This forces users to make a conscious selection rather than accidentally submitting with a default value.

  5. Improve the label appearance:

    <%= f.label :mpaa_rating, "MPAA Rating" %>

    This demonstrates Rails' flexibility in overriding default label text for better user experience.

Creating Select Dropdowns

1

Define Options Variable

Create options using options_for_select helper with an array of possible values

2

Add Blank Option

Use include_blank: true to prevent default selection and force user choice

3

Customize Labels

Pass second parameter to f.label to display user-friendly text like 'MPAA Rating'

Adding a Date-Selector Field

Date inputs are notoriously challenging in web development due to browser inconsistencies and user experience concerns. Rails' date selection helpers provide a robust, cross-browser solution that generates intuitive dropdown menus while handling complex date validation and formatting behind the scenes.

  1. Add the date selector for movie release dates:

    <%= f.select :mpaa_rating, mpaa_ratings, include_blank: true %>
       </p>
       <p>
          <%= f.label :release_date %>
          <%= f.date_select :release_date %>
       </p>

    The date_select helper automatically generates three coordinated dropdown menus for comprehensive date selection.

  2. Test the date selectors—they provide intuitive date selection, but let's optimize the order for better user experience:

    <%= f.date_select :release_date, order: [:month, :day, :year] %>

    This reorders the dropdowns to match common US date format expectations, improving form completion rates and reducing user confusion.

  3. Save and test the improved date selector layout. The month-day-year order feels more natural for most users and follows established UI patterns.

Date Select Customization

The date_select helper provides separate dropdowns for day, month, and year. Use the order parameter to arrange them logically: order: [:month, :day, :year] for American format.

Key Takeaways

1Rails form_with helper automatically generates secure forms with CSRF protection and proper HTML structure
2The form builder object (f parameter) intelligently creates appropriate form elements based on model attributes
3Use checkboxes for boolean values, radio buttons for 2-5 options, and select dropdowns for larger option sets
4Always use f.label helper instead of plain text to ensure proper label association and accessibility
5Rails automatically generates semantic IDs and names for form elements following convention over configuration
6The options_for_select helper combined with include_blank: true creates user-friendly dropdown menus
7Date selectors can be customized with order parameters to match regional date format preferences
8Proper form implementation requires careful attention to user experience details like helpful instructional text

RELATED ARTICLES