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.

Leaving a comment<br />

This generates helpers such as project_tickets_path. But for your form it’s not<br />

important what comment the project is being created for, so you use ticket<br />

_comments_path instead. This means you need to define a separate nonnested<br />

resource for your tickets and then a nested resource under that for your comments, as<br />

shown in the following listing.<br />

Listing 10.5 config/routes.rb<br />

resources :projects do<br />

resources :tickets<br />

end<br />

resources :tickets do<br />

resources :comments<br />

end<br />

The last three lines in listing 10.5 are the lines you need in order for ticket<br />

_comments_path to be defined, which will make your form work.<br />

10.1.4 The comments controller<br />

Now finally you need to generate the CommentsController so that your form has<br />

somewhere to post to. You can do this by running the following command:<br />

rails g controller comments<br />

A create action in this controller will provide the receiving end for the comment<br />

form, so you should add this now. You need to define two before_filters in this controller.<br />

The first is to ensure the user is signed in, because you don’t want anonymous<br />

users creating comments; the other is to find the Ticket object. This entire controller<br />

is shown in the following listing.<br />

Listing 10.6 app/controllers/comments_controller.rb<br />

class CommentsController < ApplicationController<br />

before_filter :authenticate_user!<br />

before_filter :find_ticket<br />

def create<br />

@comment = @ticket.comments.build(params[:comment].merge(:user =><br />

➥current_user))<br />

if @comment.save<br />

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

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

else<br />

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

render :template => "tickets/show"<br />

end<br />

end<br />

private<br />

def find_ticket<br />

B<br />

C Render template<br />

Redirect to<br />

ticket page<br />

249

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

Saved successfully!

Ooh no, something went wrong!