Per-user tags with has_many_polymorphs
December 4, 2007I 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.)





