27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

10.1.2 The comment form<br />

Leaving a comment<br />

Let’s continue building this comment form for the application, the same one to which<br />

you’ll eventually add a state-select box to complete this feature. This comment form<br />

will consist of a single text field in which the user can insert their comment.<br />

Add a single line to the bottom of app/views/tickets/show.html.erb to render the<br />

comment form partial:<br />

<br />

This line renders the partial from app/views/comments/_form.html.erb, which you<br />

now create and fill with the content from the following listing.<br />

Listing 10.3 app/views/comments/_form.html.erb<br />

New comment<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Pretty much the standard form_for here, except you use the Array-argument syntax<br />

again, which will generate a nested route. You need to do four things before this form<br />

will work.<br />

First, you must define the @comment variable in the show action in Tickets-<br />

Controller so this form_for has something to work with.<br />

Second, you need to create the Comment model and associate this with your Ticket<br />

model so you can create new records from the data in the form and associate it with<br />

the right ticket.<br />

Third, you need to define the nested resource so that the form_for knows to POST<br />

to the correct URL, one similar to /tickets/1/comments. Without this, you run into an<br />

undefined method of ticket_comments_path when the form_for tries to generate<br />

the URL by combining the classes of the objects in the array for its action.<br />

Finally, you need to generate the CommentsController and the create action<br />

along with it so that your form has somewhere to go when a user submits it.<br />

Now set up your TicketsController to use the Comment model for creating new<br />

comments, which you’ll create shortly afterward. To do this, you need to first build a<br />

new Comment object using the comments association on your @ticket object.<br />

10.1.3 The comment model<br />

The first step to getting this feature to pass is to set up the show action in your<br />

TicketsController to define a @comment variable for the comment form. To do this,<br />

change the show action, as shown in the following listing.<br />

247

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!