views:

223

answers:

0

Im learning Rails and have built a'store' application from the 'Agile Development w/ Rails' book. Ive gone beyond the lesson in the book and Im trying to add 'tags' to each product in the the store. Id then like a user to be able to click on a tag (that will be in a list in the sidebar), and have the store repopulate with those tagged product items.

At first I tried using 'Acts as Taggable (on steroids)' along with a couple other plugins but didn't have any luck getting the app to recognize the 'acts_as_taggable' line added to my products.rb model.

'Acts_as_taggable' and other tagging plugins don't seem to work well in Rails 2.3.5 (which Im using). I looked around and decided that using 'nested model forms' was the way to go - as laid out by Ryan Bates in this RailsCast: http://railscasts.com/episodes/196-nested-model-form-part-1

After making some minor tweaks (rails 2.3.4 uses _delete instead of _destroy), I was able to get the tags wired up to the products by creating a tag model that 'belongs to' a product and by adding these lines to my 'product.rb' model:

has_many :tags, :dependent => :destroy accepts_nested_attributes_for :tags, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true

So far so good, I think! Where Im stuck is creating a new view for each 'tag'. I started by creating a view for a particular 'tag' (ex: 'games') and I was able to reproduce the listings on the index page which listed everything in the store by having it route to a store/games page. However, I am not able to limit those listings to products with the 'games' tag.

Here are my methods in my products.rb file that are used on the index and the games views:

def self.find_products_for_sale find(:all, :order => "title") end

def self.find_games_for_sale Tag.find(:all, :order => "title")

And here are my methods in the store controller:

def index @products = Product.find_products_for_sale end

def calendars @products = Product.find_games_for_sale end

What am I doing wrong? Should I be creating methods in my tags.rb file instead of the products.rb file? Also, is there an easier way to view products attached to certain tags rather than creating new methods and views for each tag I want to access? Finally, are 'nested model forms' the best way to go to add tags to a Rails app?

Thanks!