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.

258 CHAPTER 10 Tracking state<br />

class Comment < ActiveRecord::Base<br />

after_create :set_ticket_state<br />

belongs_to :ticket<br />

belongs_to :user<br />

belongs_to :state<br />

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

end<br />

While you’re here, you can also set it up so that you can access the project association<br />

that the ticket association has in this model by using the delegates method:<br />

delegate :project, :to => :ticket<br />

If you call the project method on a Comment object, this method will “delegate” the<br />

project method to the ticket object, making a call exactly like ticket .project. This<br />

makes your code shorter and will come in handy later on.<br />

The symbol passed to the after_create method here is the name of the method<br />

to call for this callback. You can define this method at the bottom of your Comment<br />

model using the code from the following listing.<br />

class Comment < ActiveRecord::Base<br />

...<br />

private<br />

end<br />

Listing 10.12 app/models/comment.rb<br />

Listing 10.13 app/models/comment.rb<br />

def set_ticket_state<br />

self.ticket.state = self.state<br />

self.ticket.save!<br />

end<br />

With this callback and associated method now in place, the associated ticket’s state will<br />

be set to the comment’s state after the comment is created. When you run your feature<br />

again by running bin/cucumber features/creating_comments.feature, it still fails:<br />

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

Failed assertion, no message given. (MiniTest::Assertion)<br />

Even though you’re correctly assigning the state to the ticket, it still doesn’t display as<br />

the state in the view. But why is this? You can attempt to duplicate this issue by running<br />

the server using the rails server. By visiting http://localhost:3000, you can<br />

follow the steps inside the scenario to attempt to duplicate the behavior you’ve seen<br />

in your feature.<br />

Because you have no states in the development database, you won’t be able to<br />

reproduce this problem right away. Your feature uses the “Given there is a state<br />

called...” steps to define states, but you can’t use these in your development environment.<br />

It would be better if you added seed data to your database because then you’ll<br />

have a repeatable way of setting up the states in your application’s database.

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

Saved successfully!

Ooh no, something went wrong!