Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Associations, habtm? Polymorphic? Both?

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?

like image 980
philnash Avatar asked Nov 02 '08 23:11

philnash


1 Answers

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
like image 66
Michiel de Mare Avatar answered Sep 28 '22 10:09

Michiel de Mare