27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

104 CHAPTER 5 Nested resources<br />

5.1.4 Creating tickets within a project<br />

Create the file at app/views/tickets/new.html.erb, and put the following inside:<br />

New Ticket<br />

<br />

This template renders a form partial, which will be relative to the current folder and will<br />

be placed at app/views/tickets/_form.html.erb, using the code from the next listing.<br />

Listing 5.5 app/views/tickets/_form.html.erb<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Note that form_for is passed an array of objects rather than simply<br />

<br />

This code indicates to form_for that you want the form to post to the nested route<br />

you’re using. For the new action, this generate a route like /projects/1/tickets, and for<br />

the edit action, it generates a route like /projects/1/tickets/2. When you run bin/<br />

cucumber features/creating_tickets.feature again, you’re told the create action<br />

is missing:<br />

And I press "Create Ticket"<br />

The action 'create' could not be found for TicketsController<br />

To define this action, put it directly underneath the new action but before the private<br />

method:<br />

def create<br />

@ticket = @project.tickets.build(params[:ticket])<br />

if @ticket.save<br />

flash[:notice] = "Ticket has been created."<br />

redirect_to [@project, @ticket]<br />

else<br />

flash[:alert] = "Ticket has not been created."<br />

render :action => "new"<br />

end<br />

end<br />

Inside this action, you use redirect_to and specify an Array B—the same array you<br />

used in the form_for earlier—containing a Project object and a Ticket object. Rails<br />

B<br />

Specify array

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

Saved successfully!

Ooh no, something went wrong!