Rails STI conditional sub-classing from base class
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) dep开发者_开发百科ending 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?
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).
精彩评论