來自基類的 Rails STI 條件子類化 (Rails STI conditional sub-classing from base class)


問題描述

來自基類的 Rails STI 條件子類化 (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?

‑‑‑‑‑

參考解法

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

(by punnieTodd)

參考文件

  1. Rails STI conditional sub‑classing from base class (CC BY‑SA 3.0/4.0)

#paperclip #nested-attributes #ruby-on-rails #sti






相關問題

帶有 S3 的回形針 - 未定義的方法 (Paperclip with S3 - undefined method)

添加文件上傳進度條的最簡單方法(回形針)Apache/Paperclip/Rails (Easiest way to add file upload progress bar (paperclip) Apache/Paperclip/Rails)

EngineYard:分離代碼和資產 (EngineYard : Segregating the code & assets)

在 rails/paperclip 中處理一系列圖像 (handling an array of images in rails/paperclip)

rails - không thể tạo bản ghi với tệp đã tải lên (rails - can't build a record with uploaded file)

在保存到 Rails 模型之前打開臨時文件 (Open the temporary file before it is saved in Rails model)

Rails - 回形針 - 多張照片上傳不保存 (Rails - paperclip - Multiple photo upload not saving)

回形針不為一種型號存儲替代尺寸,但為另一種型號存儲 (Paperclip is not storing alternative sizes for one model, but does for another)

無法使用 S3 圖像的 image.to_file 使用 Paperclip gem 複製圖像 (Can't copy images with Paperclip gem using image.to_file for S3 images)

Paperclip.interpolates 隨機不返回值 (Paperclip.interpolates randomly not returning a value)

未初始化的常量 AWS::S3::NoSuchBucket (uninitialized constant AWS::S3::NoSuchBucket)

來自基類的 Rails STI 條件子類化 (Rails STI conditional sub-classing from base class)







留言討論