Let’s say that I have a Company model and a Product model, both of which have an UserUploadedImage associated with them. I want to create my UserUploadedImage in a way such that I can write image.parent and that will reference either the Product or the Company, whichever is appropriate in that case.
I realize I can store a second column in UserUploadedImage with either Product or Company and have a conditional to look up the appropriate value. I am, however, not sure where the optimal place to put this code is, or whether there is a cleaner way of achieving my goal. Thanks!
What you need to look at is Polymorphic Associations
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
Polymorphic Associations
A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model.
You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures.
Similarly, you can retrieve @product.pictures.
If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
This migration can be simplified by using the t.references form: