我有一个Upload
模型用于fileuploads,它与其他具有多态关联的模型共享。
# 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
,以便上传和处理不同的文件类型。为此,上传针对每种文件类型都有不同的列,例如image_data
,video_data
或background_data
。
现在,Upload
的关联“父母”应该只支持某些文件类型。与......相关联时。
Product
,它应该只允许图片和视频上传Announcement
,它应该只允许图片上传Site
,它应该只允许后台上传 如何根据与其父记录的关联验证Upload
模型?此验证是否应在upload.rb
或其父模型中进行?
就代码而言,Upload
应仅在与父级相关联时允许相应的字段。有点像...
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
谢谢!