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.

Tracking changes<br />

Put this new callback on a line directly above the after_create because it makes<br />

sense to have all your callbacks grouped together and in the order that they’re<br />

called in:<br />

before_create :set_previous_state<br />

Call the set_previous_state method for this callback, which you define at the bottom<br />

of the Comment model just before the set_ticket_state method, like this:<br />

def set_previous_state<br />

self.previous_state = ticket.state<br />

end<br />

The previous_state= method you call here isn’t yet defined. You can define this<br />

method by declaring that your Comment objects belongs_to a previous_state, which<br />

is a State object. Let’s put this line with the belongs_to in your Comment model:<br />

belongs_to :previous_state, :class_name => "State"<br />

Here you use a new option for belongs_to: class_name. The field in your comments<br />

table is called previous_state_id and so you call your association previous_state.<br />

To tell Rails what class this associated record is, you must use the class_name option,<br />

otherwise Rails will go looking for the PreviousState class.<br />

With this belongs_to defined, you get the previous_state= method for free and<br />

so your callback should work alright. There’s one way to make sure of this, and that’s<br />

to attempt to display these transitions between the states in your view so that your feature<br />

will potentially pass. You’ll now work on displaying these transitions.<br />

10.3.3 Displaying changes<br />

When you display a comment that changes a ticket’s state, you want to display this<br />

state transition along with the comment.<br />

To get this text to show up, add the following lines to app/views/comments/<br />

_comment.html.erb underneath the h4 tag:<br />

&rarr;<br />

<br />

This is almost correct, but there’s a slight problem. Your callback<br />

will set the previous_state regardless of what the current state is,<br />

and in this case you can end up with something like figure 10.12.<br />

To stop this from happening, you can wrap this code in an if<br />

statement, like this:<br />

<br />

&rarr; <br />

<br />

Now this text will only show up when the previous state isn’t the same as the current<br />

state.<br />

265<br />

Figure 10.12<br />

State transition<br />

from itself to itself

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

Saved successfully!

Ooh no, something went wrong!