5

In my Rails app I have three models, Projects, BlogPosts and Images. Projects and BlogPosts can have many linked images and an image can be linked to a Project, a BlogPost or both.

What is the best way of setting up the associations to make this work in Rails?

philnash
  • 70,667
  • 10
  • 60
  • 88

1 Answers1

9

I'd tease out the habtm into a separate model class, ImageLink. Then you'd get:

Project
  has_many :image_links, :as => :resource
BlogPost
  has_many :image_links, :as => :resource
ImageLink
  belongs_to :image
  belongs_to :resource, :polymorphic => true
Image:
  has_many :image_links
Michiel de Mare
  • 41,982
  • 29
  • 103
  • 134
  • 2
    This is not really a "teased out" habtm, because it really is the same as a habtm (with ImageLink as the habtm-table), but the advantage of this method is that you combine two habtms into one. – Jeroen Heijmans Nov 03 '08 at 08:30
  • 2
    Thanks, I added has_many :through associations to this too, finding in the process that that doesn't work from the Image side of things, but in this case that doesn't matter as I only want to get Images linked to Projects rather than the other way round. – philnash Nov 03 '08 at 11:30