Rails 5 + Shrine多文件上传

3

我正在尝试使用多态关联和Shrine来实现多文件上传。

class Campaign < ApplicationRecord
  has_many :photos, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :photos, allow_destroy: true
end

class Photo < ApplicationRecord
  include ImageUploader::Attachment.new(:image)
  belongs_to :imageable, polymorphic: true
end

在阅读文档后,我能够保存照片。
请指导如何验证图像在imageable范围内的唯一性。
我知道可以为每个原始版本生成一个签名,但这是正确的方法吗?
谢谢。

1个回答

2
生成签名是唯一的方法来判断两个文件是否具有相同的内容,而不必加载这两个文件到内存中(这是您应该始终避免的)。另外,使用签名意味着如果您将签名保存到列中,则可以使用数据库唯一性约束和/或ActiveRecord唯一性验证。 下面是使用Shrine实现此功能的示例:
# db/migrations/001_create_photos.rb
create_table :photos do |t|
  t.integer :imageable_id
  t.string  :imageable_type
  t.text    :image_data
  t.text    :image_signature
end
add_index :photos, :image_signature, unique: true

# app/uploaders/image_uploader.rb
class ImageUploader < Shrine
  plugin :signature
  plugin :add_metadata
  plugin :metadata_attributes :md5 => :signature

  add_metadata(:md5) { |io| calculate_signature(io) }
end

# app/models/image.rb
class Photo < ApplicationRecord
  include ImageUploader::Attachment.new(:image)
  belongs_to :imageable, polymorphic: true

  validates_uniqueness_of :image_signature
end

谢谢!我已经花了一整天的时间来研究使用jQuery进行直接上传。 :) - Anton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接