Route to Create Pages1:18 with Jay McGavren
When we submit our form for a new Page, we see the error "No route matches [POST] '/pages'". Notice that it's not saying [GET] '/pages', it's saying POST. We only have GET request routes for pages right now, though. We'll need to add a POST route.
When you're adding new data to the server, your browser sends an HTTP POST request. So, when you click the submit button on an HTML form, that's what your browser sends to the server: a POST request with the form contents.
For this reason, setting up a form to add new instances of a resource usually requires two routes in your
Suppose we were setting up a form for new
Page records. We'd first need a route to GET the HTML form:
get '/pages/new', to: 'pages#new'
Then we'd need a second route to accept the POST request when the form is submitted:
post '/pages', to: 'pages#create'
When we submit our form for a new page we see the error, 0:00 no route matches post /pages. 0:03 Notice that it's not saying get pages, tt's saying post. 0:06 HTTP Get requests are intended for getting data from the server. 0:11 When you're adding new data and 0:15 you're supposed to use an HTTP POST request instead. 0:16 So when you click the submit button on an HTML form 0:20 a POST request as what your browser sense to the server. 0:23 We only have get requests routes for 0:27 pages right now though, we'll need to add a post route. 0:29 We do that by calling the post method instead of the get method within route 0:32 that are RB. 0:36 We'll route all post requests for 0:37 the /pages path to the pages controllers create method. 0:40 We already have a get /pages route but 0:48 it's okay to have a post /pages route as well. 0:51 The two different request types get routed separately. 0:54 There's also no risk of the router confusing a post request with the other 0:57 get request, so we don't have to worry about what order we add the route in. 1:01 If we save this and submit our form again from our browser, 1:05 we'll see the action create cannot be found for PagesController. 1:08 It looks like our request is being routed to the right place. 1:12 Now we just need to add the create method to handle it. 1:15
You need to sign up for Treehouse in order to download course files.Sign up