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.

248 CHAPTER 10 Tracking state<br />

Listing 10.4 app/controllers/tickets_controller.rb<br />

def show<br />

@comment = @ticket.comments.build<br />

end<br />

This will use the build method on the comments association for your @ticket object<br />

(which is set up by the find_ticketbefore_filter) to create a new Comment object<br />

for the view’s form_for.<br />

Next, you generate the Comment model so that you can define the comments association<br />

on your Ticket model. This model’s going to need to have an attribute called<br />

text for the text from the form, a foreign key to link it to a ticket, and another foreign<br />

key to link to a user record. Let’s generate this model using this command:<br />

rails g model comment text:text ticket_id:integer user_id:integer<br />

Then run the migration for this model on both your development and test databases<br />

by running these familiar commands:<br />

rake db:migrate<br />

rake db:test:prepare<br />

With these done, your next stop is to add the associations to the Ticket and Comment<br />

models. For this, you add this line to app/models/ticket.rb directly under the<br />

accepts_nested_attributes_for :assets line:<br />

has_many :comments<br />

Add a validation to your Comment model to validate the presence of text for the<br />

records by adding this line to app/models/comment.rb:<br />

validates :text, :presence => true<br />

This will help your second scenario pass, because it requires that an error message is<br />

displayed when you don’t enter any text. You also add a belongs_to association definition<br />

to this model, given that you have a user_id column in your comments table:<br />

belongs_to :user<br />

When you run your feature at this mid-point, you’re told that it can’t find the routing<br />

helper that form_for is trying to use:<br />

undefined method `ticket_comments_path' for ...<br />

This is because you don’t have a nested route for comments inside your tickets<br />

resource yet. To define one, you need to add it to config/routes.rb.<br />

Currently in your config/routes.rb you’ve got the tickets resource nested inside the<br />

projects resource with these lines:<br />

resources :projects do<br />

resources :tickets<br />

end

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

Saved successfully!

Ooh no, something went wrong!