Controller Action for New Pages1:48 with Jay McGavren
We're trying to set up an HTML form for new Page objects. We've defined a route for the /pages/new path that directs to the new method on PagesController. Now we just need to define that method.
We're trying to set up an HTML form for new page objects. 0:00 We've defined around for 0:04 the /pages/new path that directs of the new method on pages controller. 0:05 Now we just need to define that method. 0:11 So we'll visit our pages controller in our editor and 0:13 add a new method here at the bottom. 0:16 The first thing the method needs to do is create a new blank page object and 0:21 assign it to an instance variable that we'll use when we create our form. 0:25 When we edit our view in a moment, 0:30 we're going to call a method named form_for to setup the HTML form. 0:32 Form_for it takes a model object, looks at its attributes, and 0:36 uses those attributes to pre populate the form's fields. 0:40 Now this might not seem like something we want since this is a form for 0:43 a new object. 0:46 In this case all of the form fields need to be blank. 0:47 But that's okay, we'll just create a new model object. 0:50 All of its attributes will default to nil. 0:53 When form_for looks at the attributes it will just set the form's fields to blank 0:56 values. 1:00 Why go to all this trouble? 1:01 For one thing we might someday want to set default to attribute values, 1:03 even on a new model object. 1:06 In that case we can just set the object attributes and 1:09 the form fields will be set the same way. 1:11 Also set in the form up this way will allow us to reuse the same form code for 1:14 both creating new objects and editing existing objects. 1:18 We'll see how that works later in the course. 1:22 So we need a page object with empty attributes to be accessible within our 1:24 view to base our form off of. 1:28 As always we make an object accessible within our 1:30 view by assigning it to an instance variable. 1:33 Variable and we get a page object with empty attributes by calling Page.new. 1:35 Be sure to save that when you're done. 1:41 Next, we'll use that new object in a view to create an empty form. 1:44
You need to sign up for Treehouse in order to download course files.Sign up