5.2 The First Form

To create a form within this template, you will use a form builder. The
primary form builder for Rails is provided by a helper method called
form_for. To use this method, add this code into
app/views/posts/new.html.erb:
<%= form_for :post do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

If you refresh the page now, you'll see the exact same form as in the
example. Building forms in Rails is really just that easy!

When you call form_for, you pass it an identifying object for this form.
In this case, it's the symbol :post. This tells the form_for helper what
this form is for. Inside the block for this method, the FormBuilder
object — represented by f — is used to build two labels and two text
fields, one each for the title and text of a post. Finally, a call to
submit on the f object will create a submit button for the form.

There's one problem with this form though. If you inspect the HTML that
is generated, by viewing the source of the page, you will see that the
action attribute for the form is pointing at /posts/new. This is a
problem because this route goes to the very page that you're on right at
the moment, and that route should only be used to display the form for a
new post.

The form needs to use a different URL in order to go somewhere else.
This can be done quite simply with the :url option of form_for.
Typically in Rails, the action that is used for new form submissions
like this is called "create", and so the form should be pointed to that
action.

Edit the form_for line inside app/views/posts/new.html.erb to look like
this:
<%= form_for :post, url: posts_path do |f| %>

In this example, the posts_path helper is passed to the :url option.
What Rails will do with this is that it will point the form to the
create action of the current controller, the PostsController, and will
send a POST request to that route.

By using the post method rather than the get method, Rails will define a
route that will only respond to POST methods. The POST method is the
typical method used by forms all over the web.

With the form and its associated route defined, you will be able to fill
in the form and then click the submit button to begin the process of
creating a new post, so go ahead and do that.