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.

Sending ticket notifications<br />

Here you must do two things: define the watchers association and add the ticket<br />

owner to the watchers list when the ticket is created.<br />

You use another has_and_belongs_to_many association to define the watchers<br />

collection, this time in your Ticket model. To define it, put this code inside the<br />

Ticket model, along with the other has_and_belongs_to_many for tags:<br />

has_and_belongs_to_many :watchers, :join_table => "ticket_watchers",<br />

:class_name => "User"<br />

Here you pass the :join_table option to specify a custom table name for your<br />

has_and_belongs_to_many. If you didn’t do this, then the table name would be<br />

inferred by Rails to be ticket_users, which doesn’t really explain the purpose of this<br />

table as much as ticket_watchers does. You pass another option too, :class_name,<br />

which tells your model that the objects from this association are User objects. If you<br />

left this option out, Active Record would imply that you wanted the Watcher class<br />

instead, which doesn’t exist.<br />

You can create a migration that can be used to create this table by using this<br />

command:<br />

rails g migration create_ticket_watchers_table<br />

Unfortunately, the migration won’t read your mind in this instance, so you need to<br />

open it and change it to resemble the following listing.<br />

Listing 12.2 db/migrate/[timestamp]_create_ticket_watchers_table.rb<br />

class CreateTicketWatchersTable < ActiveRecord::Migration<br />

def change<br />

create_table :ticket_watchers, :id => false do |t|<br />

t.integer :user_id, :ticket_id<br />

end<br />

end<br />

end<br />

Remember: you need to specify the id option here so that your join table doesn’t have<br />

a primary key.<br />

Let’s save and then run this file using rake db:migrate, and let’s not forget to run<br />

rake db:test:prepare either.<br />

Now that you have your watchers method defined, you need to add the user who<br />

creates a ticket to the list of watchers for that ticket. You can do this by using an<br />

after_create callback on your Ticket model like this:<br />

after_create :creator_watches_me<br />

To define the creator_watches_me method, you put the following code at the bottom<br />

of the Ticket class definition:<br />

private<br />

def creator_watches_me<br />

self.watchers

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

Saved successfully!

Ooh no, something went wrong!