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.
What you’re looking for is called polymorphism. Basically, you’re not associating a model with a fixed other model through a single
other_model_idfield, but you keep track of two fields:other_model_classandother_model_foreign_key. That way you can associate aDocumentwithclass: User, id: 42in one case andclass: Course, id: 42in another. There’s a Behavior in the Bakery, which should be a good place to start.