← Back to Upcase

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


(Cyle Hunter) #1

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.


(Cyle Hunter) #3

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