I’m attempting to create a polymorphic imaging system which would allow various objects to have a cover image and additional images. Would I be correct in creating an Image model with belongs_to :imageable ? Or, should I separate out my logic so each model that will inherit image capabilities be given a separate polymorphic associations for both cover images and additional images?
Then, once I have setup has_many relationship, how do I manage it? In a perfect world I would want to be able to call @object.images.cover? and @object.images.additionals.
Create an
imagestable for your polymorphic association that has acoverboolean field, indicating if the image in the record is a cover image:Then include
has_many :images, :as => :imageableon your objects. Now to have the@object.coverand@object.additionalsthat you desire, you have two options. The first is to create a Concern module to mix-in to your Object classes. The second is to subclass. I’ll talk about the Concern approach here because it is a method being pushed in Rails 4, and subclassing is already familiar to most programmers.Create a module inside
app/models/concerns:You can now mix-in this concern to your object classes. For example:
You will also have to include your concerns from
app/models/concerns, since they won’t be loaded automatically (in Rails 4, any file in that directory will be included by default).