Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 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?

like image 341
punnie Avatar asked Mar 06 '26 17:03

punnie


1 Answers

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).

like image 59
Todd Avatar answered Mar 09 '26 11:03

Todd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!