Search code examples
databasehas-and-belongs-to-manyrelationshipspolymorphism

Polymorphic vs HABTM relationships for a tagging system


I am currently making a database for a rails application. This schema involves three models: Photo, Object and Tag. Both photos and objects need to be "taggable".

  • Tags are unique
  • Tags can belong to a Photo, or an Object, or both

Rails offers a polymorphic association which results in tags having a belongs_to relationship with both Photo and Object; however it does not allow a Tag to belong belong to both.

One might solve this by having two independent HABTM relationships for 'tags to photos' and 'tags to objects'.

I was wondering if there was more efficient way of achieving this; or if perhaps I am approaching the problem from the wrong direction?


Solution

  • Tags are a way of saying something about a thing.

    It might not make sense to use a single set of tags to say something about every kind of thing. I can imagine tags like "1024x768" and "shot-with-Olympus-camera" being useful if you're trying to say something about a photo, but not really useful if you're trying to say something about an object.

    Let's say I use a tag like "blue" to refer to both a photo and to an object. Does {photo_id, "blue"} mean the same thing as {object_id, "blue"}? I don't think it does.

    It seems to me the most efficient solution is to use one set of tags to say something about photos, and another set of tags to say something about objects. It's also likely to be more friendly to your users.