Add A New Job Form

Goals

  • creat a HTML form using Rails form helpers

  • Learn to read the Rails server output

  • Update the controller so that the form saves submissions to the database

  • Learn how to handle parameters

Side Note: Web forms are not perfectly straightfoward

They're like, the most basic thing about the internet, other than cat gifs, right? So they should be straightforward, right? WRONG! They are exciting and just complicated enough to bake your noodle a bit.

But don't worry, Rails has strong opinions about forms, so we won't have to do too much typing.

Setting up the page for the form

Let's take a look at our handy routes, which can help us figure out what we need to do. We're going to follow the same pattern that we did for the main /jobs page.

First, visit the routing page at http://localhost:3000/rails/info, and find the route for /jobs/new.

That's the one we want for our form. Let's visit that page and see what it says

Steps

Step 1: Visit /jobs/new

open http://localhost:3000/jobs/new in your browser

Error! Woo!!!

The action 'new' could not be found for JobsController

This looks familiar! do you remember the next step?

Step 2: add an action to the controller

Let's add a method to our jobs controller called new:

def new
  @job = Job.new
end

refresh http://localhost:3000/jobs/new in your browser

Error! Woo!!!

JobsController#new is missing a template for request formats: text/html

do you remember how to add the template? Which file do you need to create?

Step 3: create a view

Under app/views/jobs, add a file called new.html.erb. This will be our form. Add some html to the template to keep things moving along:

<h1>Add a job</h1>

there should be no error now

Step 4: Add a form!

Rails has handy helpers for forms. We'll be using a form helper specifically made for use with a model.

In the view file you were just editing (app/views/jobs/new), add the following code:

<%= form_with(model: @job, local: true) do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div>
    <%= form.label :description %>
    <%= form.text_area :description, size: '60x6' %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

Save that file, and reload the page.

Now we should see our mostly unstyled form!

Now would be a good time to commit to git

Discussion: Form HTML


What HTML did the form helpers produce? Using the web inspector, look through the form code and compare it to the file you've been working on in VS Code.

Next Step: