I have a polymorphic association on an Image
model and need to have two associations on it from a Place
model. Something like:
class Place < ActiveRecord::Base
has_many :pictures, as: :imageable, class_name: 'Image'
has_one :cover_image, as: :imageable, class_name: 'Image'
end
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
This obviously doesn't work has the Image
model doesn't know the difference between pictures and cover_image and every image is stored with
#<Image ... imageable_id: 17, imageable_type: "Place">
I was thinking about adding a imageable_sub_type
column to Image
to store a subtype.. So my images would look like:
#<Image ... imageable_id: 17, imageable_type: "Place", imageable_sub_type: "cover_image">
I can easily retrieve only the images with that subtype from my association in Place
:
has_one :cover_image, -> { where(imageable_sub_type: 'cover_image'), as: :imageable, class_name: 'Image'
But I don't find a way to set this value while adding an image to a Place
(actually it is always set to nil
).
Is there a way to do that?
I tried to do it this way: https://stackoverflow.com/a/3078286/1015177 but the problem remains the same, the imageable_sub_type
remains nil
.