An Update Action

We've successfully created a form for editing an existing Page, and populated it with the Page's attributes. But if we submit the form, we see that a so-called HTTP PATCH request is being sent by the browser, and there's no route for that type of request. So to process these requests, we'll need to go into routes.rb add a PATCH route.

A controller action to update an existing model object usually performs these operations:

def update
# Look up the existing model record based
# on an ID from the request path.
@page = Page.find(params[:id])
# Filter the form parameters to ensure no
# malicious parameters were added.
page_params = params.require(:page).permit(:title, :body, :slug)
# Use the filtered parameters to update
# the existing model record.
@page.update(page_parameters)
# Redirect the browser to another location
# so that it doesn't just sit there displaying
# the submitted form.
redirect_to @page
end

0:00

We've successfully created a form for
editing and the existing page and

0:04

populated it with the pages attributes,
but if we submit the form,

0:08

we see that the so-called HTTP patch
request is being sent by the browser and

0:12

there's no route for that type of request.

0:15

When you're modifying existing data on
the server rather than adding new data,

0:19

you're supposed to use a put or
patch request rather than a post request.

0:24

So when you click the submit
button on the edit form,

0:26

that's what your browser sends
to the server, a patch request.

0:30

Actually, it's technically still a post
request coming for the browser but

0:34

it has some added parameters indicating it
should be treated as a patch request and

0:38

Rails converts the request
type to patch internally.

0:41

So to process these requests we'll need to
go into routes.rb and add a patch route.

0:46

Just as we use the get method for
get routes and the post method for

0:49

post routes, we call the patch
method to create a patch route.

0:54

We can do it here at the bottom of
the list, the order doesn't matter.

0:57

Let's go to our browser and
look at the HTML for the edit form.

1:02

We can see that its action attribute
is set to submit to a path of pages

1:06

followed by the page ID.

1:08

The ID is provided so that we can look the
record up in the database just like we do

1:12

with the show and edit pass.

1:14

Once we found the record in the database
we can use the form parameters

1:17

to update it.

1:19

So that's the path we use in our route
slash pages followed by another slash and