This is a copy/paste from my question over at 
StackOverflow<http://stackoverflow.com/questions/5750963/implementing-a-tagging-system-in-rails>so
 feel free to answer there if you want some reputation.

I'm trying to implement a tagging system in a Rails app similar to the one 
StackOverflow uses (where users enter in tags in a freeform textbox). I'm 
aware that there are gems that can do this, but I wanted to try to implement 
it myself for the learning experience. I got it to work, but since I'm a 
Rails newbie I'm concerned I'm not doing it the "right way". 

Here's my current implementation:

def Post
  attr_accessor :tag_names

  has_and_belongs_to_many :tags

  after_save :update_tags

  private
    def update_tags
      tags.delete_all

      if tag_names.to_s == ''
        return
      end

      tag_names.split(/,/).each do |tag_name|
        tag_name.strip!
        tag = Tag.find_or_create_by_name(tag_name)

        if !tags.exists?(tag.id)
          tags << tag
        end
      end
    end
end

This makes it easy for me to set up the tags for a post since all I have to 
do is set the "tag_names" attribute on my post object. When I save the post 
object, the after_save event fires and executes my update_tags function 
which then handles creating tags and linking the post to them.

Are there any problems with my implementation?


-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to