views:

306

answers:

1

I have three tables: "users", "courses" and "documents". I would like to upload documents to users as well as to courses, so I would need two belongsTo-relations for the Document model. Some belong to one model, some to the other.

Is there a simple solution to construct these relations?

How could I set up the "add"-actions?

I know I could set up two join tables and use HABTM, but that doesn't feel right. A document belongs only to one other item. Besides, I want to be able to extend the relations to more models if neccessary.

+1  A: 

What you're looking for is called polymorphism. Basically, you're not associating a model with a fixed other model though a single other_model_id field, but you keep track of two fields: other_model_class and other_model_foreign_key. That way you can associate a Document with class: User, id: 42 in one case and class: Course, id: 42 in another. There's a Behavior in the Bakery, which should be a good place to start.

deceze
+1 This is a powerful behavior that works great. I've used it with great success on a couple of projects.
Rob Wilkerson