Rails STI 从基类进行条件子类化

发布于 2024-10-08 05:37:41 字数 805 浏览 2 评论 0原文

我正在开发一个项目,其中有一个实体,该实体可能有两种资产:基本上是图片视频

由于我希望所有资源都位于同一个表中,并且为图片视频提供一个上传表单,因此我使用具有图片的单表继承Video 源自 Asset 类。另外,我将根据它是视频还是图片来运行不同的验证/回调。

我使用回形针来处理上传过程,我的想法是当上传文件并用它创建资产时,应用程序将实例化正确的子类(图片视频< /em>) 取决于上传文件的 mime 类型。

这是我的类的草图:

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

我的想法是在 Asset 类上实现 before_save 回调,并尝试在那里实例化正确的类,但我不确定如何去做或者如果这是一个好主意。

对此有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

壹場煙雨 2024-10-15 05:37:41

虽然您应该喜欢胖模型和瘦控制器,但对我来说,这似乎更好地放置在控制器中。我的主要理由是,通过在您的 Asset 模型中执行此操作,您将基本类型与其子类型耦合起来,这对我来说并不合适(尽管我看到 API 一直在这样做)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文