3

I'm developing a project where I have an entity which may have two kinds of assets: Pictures and Videos, basically.

Since I want all the assets to be on the same table and a single upload form for either Pictures or Videos, I'm using Single Table Inheritance having both Picture and Video descending from the Asset class. Also, I'll be running different validations/callbacks depending on whether it is a Video or a Picture.

I'm using paperclip to deal with the upload process, and my idea is to when uploading a file and creating an Asset with it, the application will instantiate the correct subclass (Picture or Video) depending on the mime-type of the uploaded file.

This is a sketch of my classes:

class Project < ActiveRecord::Base
  has_many :assets
  accepts_nested_attributes_for :assets
end

class Asset < ActiveRecord::Base
  belongs_to :project
  has_uploaded_file :content, ...
end

class Picture < Asset
  validate :image_size
  ...
end

class Video < Asset
  after_save :convert_format
  ...
end

My idea is to implement a before_save callback on the Asset class and try to instantiate the correct class there, but I'm not sure how to do it or if it's a good idea.

Any idea about this?

punnie
  • 2,404
  • 4
  • 17
  • 32

1 Answers1

1

While you should favor fat models and skinny controllers, this to me seems better placed in the controller. My primary rationale is that by doing this in your Asset model you are coupling a base type to its subtypes, which doesn't feel right to me (although I see APIs do it all the time).

Todd
  • 3,438
  • 1
  • 27
  • 36
  • 1
    I'll accept this answer because it came close to what I ended up doing and pointed me in the right direction: I discarded the nested modelling functionality and chose to save the nested model manually. The "factory" logic that creates the right sub-class is indeed in the Project controller, but it can be easily ported into its model, which I'll end up doing as soon as I finish the rest of the important stuff. A simplified snippet that depicts the solution is available at http://pastie.org/1522024. – punnie Feb 02 '11 at 16:36