Context-sensitive validations / methods on model with polymorphic association?

I have the following setup using a polymorphic association:

class Upload < ActiveRecord::Base
  belongs_to :uploadable, polymorphic: true
end

class UploadStore
  has_many :uploads, as: :uploadable, dependent: :destroy
end

class Entry
  has_many :submissions, as: :uploadable, dependent: :destroy
end

Depending on which class is on the receiving end of the uploadable model, I would like to apply custom validations as appropriate. For instance, if the Upload is being added to an Entry object then the uploadā€™s file extension must conform to a list of extensions that are only valid for an Entry upload.

STI comes to mind, but I havenā€™t seen any examples of STI & Polymorphic Associations used in conjunction, usually itā€™s one of the other. I donā€™t want to litter my Upload model with type conditionals, but still want to be able to take advantage of the polymorphic association.

Iā€™m over-complicating this. My original polymorphic setup was fine, I just needed to front my upload model with subclasses containing any unqiue validations where appropriate and associate to those models instead of the upload model directly.

class Submission < Upload

  #custom validations...

end
1 Like