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.

Changing a ticket’s state<br />

You’re now going to render this partial underneath the “Created by” line on app/<br />

views/tickets/show.html.erb using the following line:<br />

<br />

You’re using the short form of rendering a partial here once again, and you conditionally<br />

render it if the ticket has a state. If you don’t have the if at the end and the<br />

state is nil, this will raise an exception because it will try to determine the model<br />

name of nil.<br />

To get this state method for your Ticket, you should add the association method<br />

to the model. This method should go directly above the belongs_to :user line in<br />

app/models/ticket.rb:<br />

belongs_to :state<br />

If you run the feature again it will fail because there’s nothing shown in the #ticket<br />

.state element:<br />

And I should see "Open" within "#ticket .state"<br />

is not true. (Test::Unit::AssertionFailedError)<br />

This is because you’re updating the state on the Comment object you’re creating, not<br />

the associated Ticket object! You’re trying to get the new state to display on the ticket<br />

object so that the users of the application can change the state of a ticket when they<br />

add a comment to it. For this to work, you need to define a callback in your Comment<br />

model.<br />

10.2.3 Callbacks<br />

When a user selects a state from the drop-down box attached to the comment form on<br />

a ticket’s page, you want that ticket’s state to be updated with what that user picked.<br />

To do this you can use a callback to set the ticket’s status when you change it<br />

through the comment form. A callback is a method that’s called either before or after<br />

a certain event. For models, there are before-and-after callbacks for the following<br />

events (where * can be substituted for either before or after):<br />

� Validation (*_validation)<br />

� Creating (*_create)<br />

� Updating (*_update)<br />

� Saving (*_save)<br />

� Destruction (*_destroy)<br />

You’re able to trigger a specific piece of code or method to run before or after any of<br />

these events. The Saving item in the list refers to when a record is saved to the database,<br />

which occurs when a record is created or updated. For your Comment model you want<br />

to define a callback that occurs after a record has been created, and for this you use the<br />

after_create method at the top of your Comment model, as well as a ticket association,<br />

transforming this model into the code shown in the following listing.<br />

257

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

Saved successfully!

Ooh no, something went wrong!