我有一个Upload
文件上传模型,它在具有多态关联的其他模型之间共享。
# upload.rb
class Upload < ApplicationRecord
include ImageUploader[:image]
include VideoUploader[:video]
include BackgroundUploader[:background]
belongs_to :uploadable, polymorphic: true
end
# product.rb
class Product < ApplicationRecord
has_many :uploads, as: :uploadable, dependent: :destroy
end
# announcement.rb
class Announcement < ApplicationRecord
has_many :uploads, as: :uploadable, dependent: :destroy
end
# site.rb
class Site < ApplicationRecord
has_many :uploads, as: :uploadable, dependent: :destroy
end
...
Upload
连接到不同的Shrine上传器,例如ImageUploader
,BackgroundUploader
或VideoUploader
, 以上传和处理不同的文件类型。为此,Upload 为每种文件类型设置了不同的列,例如image_data
、video_data
或background_data
。
现在,一个关联的“父母”Upload
应该只支持某些文件类型。当关联到…</p>
Product
,它应该只允许上传图片和视频Announcement
,它应该只允许图片上传Site
,它应该只允许后台上传
如何Upload
根据与父记录的关联来验证模型?这种验证应该发生在它的父模型中upload.rb
还是在它的父模型中?
就代码而言,Upload
应该只允许与父级关联的各个字段。像……</p>
if upload.parent == product
validate presence image_data xor video_data
if upload.parent == announcement
validate presence of image_data
if upload.parent == site
validate presence of background_data
谢谢!