3

Well, I have a table with images, each image is tagged with a HABTM relation through a join table.

What I want to do is show related images in the page the image is being shown, by matching images with the same tags.

Can this be done efficiently with the current join table or I should generate joins between images in another table each time a new image is created?

Charles
  • 50,943
  • 13
  • 104
  • 142
Zequez
  • 3,399
  • 2
  • 31
  • 42

1 Answers1

3

I recommend you consider switching to using has_many :items, :through => :link_table
It's become the new standard and it's a great approach because you get more flexibility 'baked in' and the structure is also ready for easy expansion and growth without major rework, e.g. adding new attributes is very easy. 'new attributes' are frequently date fields.
So you can add the regular timestamps fields (created and updated) and people also find other date fields like 'completed_on', 'authorized_on', 'terminated_on', 'activated_on', 'sold_on', etc. useful, depending on the application use cases.

class Image < ActiveRecord::Base
  has_many :image_tags
  has_many :tags, :through => :image_tags
end

class ImageTag < ActiveRecord::Base
  belongs_to :image
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :image_tags
  has_many :images, :through => :image_tags
end

You will still see a lot of examples of HABTM and it does still work. There are certainly cases where it may still make sense to use it but as HMT does them anyway, KISS says use 'one way'.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 2
    Then you can do things like \@image.tags to get all tags for a specific image, or \@tag.images to get all images associated with a tag – Faisal Sep 29 '11 at 13:03
  • With the proper migration for the `ImageTag` table and the resulting methods `@image.tags` and `@tag.images`, @Zequez has all he needs. – mliebelt Sep 29 '11 at 13:04
  • sorry, had to do \@ because the comment system thought I was linking stack overflow users :s... just remove the backspace before the at sign – Faisal Sep 29 '11 at 13:04
  • Hey Faisal, would the little backticks (top left) help? They are a different way to highlight code I recently discovered - you use two of them - help with dong the at ? here let me try: `@` lets see how that looks. You may already know them. – Michael Durrant Sep 29 '11 at 13:09
  • @michaeldurrant omg.. how did I forget about escaping code? silly me.. thanx for the info :) – Faisal Sep 29 '11 at 13:43