blog@osd.se

Just another WordPress weblog
  • Home
  • About me
  • My website (in Swedish)

Per-user tags with has_many_polymorphs

December 4, 2007

I got a question about how I implemented per-user tagging with has_many_polymorphs. He suggested that I wrote a post about it. And why not?

Most posts that I have read about combining users and tagging was about adding the user scope to the tagging, which means that you still have a global set of tags (for example like del.icio.us). I wanted each user to have his, or her, own set of tags – a tag belongs to a user – like Gmail.

This is how I did it:

I used the tagging generator that comes with HMP and generate the Tag and Tagging models. From before, I had the User and Transfer (my taggable) models. Each Transfer belongs to a User.

To the Tag model, add “belongs_to :user” and “validates_uniqueness_of :name, :scope => [:user_id, :name]“.

Add “belongs_to :user” to the Tagging model. The taggings will belong to a user through the tag (and also through the taggable in my case, but that shouldn’t be a requirement).

You also need to modify the “_add_tags” function in the generated file “lib/tagging_extensions.rb”. When the Tag is found or created, you need to do “tag = Tag.find_or_create_by_name_and_user_id(tag_name, user.id)”, instead of “tag = Tag.find_or_create_by_name(tag_name)”, which I believe it was originally. Otherwise it doesn’t set the user_id in the tag.

Of course you have to update your migrations for the Tag model. You need to add a user_id column to it.

That should be it, but I might have forgotten something.

(Thanks to Alexander Hoth for the idea to this post.)

Categories
Programming, Rails
Comments rss
Comments rss
Trackback
Trackback

« Prototype is a prototype? How should I work with SQL in Rails? »

Leave a Reply

Click here to cancel reply.

Categories

  • Games (4)
  • Music (7)
  • Programming (5)
  • Rails (4)
  • Stupid (1)
  • Swedish (2)
  • TV (1)
  • Uncategorized (1)
  • Web (4)

Links

  • 456 Berea Street
  • Ayende @ Rahien
  • Calle’s Journal
  • Discobelle
  • Manolo
  • Matthew Garrett’s Journal
  • Maximum Flow
  • Månhus (in Swedish)
  • My work
  • MySQL Performance Blog
  • ReadWriteWeb
  • Sphinx search engine
  • The Sartorialist

Archives

  • October 2009
  • December 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox