In this second part of a four-part series on how to add tagging support to an ecommerce website using Ruby on Rails, you'll learn what modifications you need to make so that items in your system can be tagged without breaking things. This article is excerpted from chapter seven of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
In Chapter 3, we created the Book model. Before creating the Tagmodel, we need to modify theBookmodel so that it can be tagged. This is a simple operation. Just add theacts_as_taggablemethod call to the model, as shown here:
class Book < ActiveRecord::Base acts_as_taggable
This gives us access to theacts_as_taggableAPI methods listed in Tables 7-1 and 7-2. We can now do things likeBook.find_by_title('The Satanic Verses').tag('Novel, Blasphemous')andBook.find_tagged_with(:any => 'Blasphemous')with the model. As you can see, the code reads almost like a sentence written in English.
Next, create the ActiveRecord model for thetagstable by executing thegeneratescript:
We tell thegeneratescript not to generate a migration file, since we already created it manually. You can open theapp/models/tag.rband examine it. You should see the following code:
class Tag < ActiveRecord::Base end
TheTag model doesnít include a mapping to theBook model. This means you canít access the books that are associated with a tag by calling, for example,Tag.find(1).books. This wonít be a problem, as we will use theacts_as_taggableAPI instead, which does the same work with theBook.find_tagged_withmethod. However, if you need it, you can add the mapping by addinghas_and_belongs_to_many :booksto theTagmodel.