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.

290 CHAPTER 11 Tagging<br />

To define the tags_tickets table, put this code in the change section of your db/<br />

migrate/[timestamp]_create_tags.rb migration:<br />

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

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

end<br />

The :id => false option passed to create_table here tells Active Record to create<br />

the table without the id field, because the join table only cares about the link between<br />

tickets and tags, and therefore does not need a unique identifier.<br />

Next, run the migration on your development database by running rake<br />

db:migrate, and on your test database by running rake db:test:prepare. This will<br />

create the tags and tags_tickets tables.<br />

When you run this scenario again with bin/cucumber features/creating<br />

_tickets:48, it is now satisfied that the tags method is defined and moves on to complaining<br />

that it can’t find the tag you specified:<br />

And I should see "browser" within "#ticket #tags"<br />

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

This failure is because you’re not doing anything to associate the text from the Tags<br />

field to the ticket you’ve created. You need to parse the content from this field into<br />

new Tag objects and then associate them with the ticket you are creating, which you’ll<br />

do right now.<br />

11.1.6 Displaying a ticket’s tags<br />

The params[:tags] in TicketsController’s create is the value from your Tags field<br />

on app/views/tickets/_form.html.erb. This is also the field you need to parse into Tag<br />

objects and associate those tags with the Ticket object you are creating.<br />

To do this, alter the create action in TicketsController by adding this line<br />

directly after@ticket.save:<br />

@ticket.tag!(params[:tags])<br />

This new tag! method will parse the tags from params[:tags], convert them into new<br />

Tag objects, and associate them with the ticket. You can define this new method at the<br />

bottom of your Ticket model like this:<br />

def tag!(tags)<br />

tags = tags.split(" ").map do |tag|<br />

Tag.find_or_create_by_name(tag)<br />

end<br />

self.tags

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

Saved successfully!

Ooh no, something went wrong!