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

浏览完文档后,我可以保存照片。
请告知如何在可成像范围内验证图像的唯一性。
我知道每个原始版本都可以生成一个签名,但这是正确的方法吗?
谢谢。

4

1 回答 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
于 2017-05-26T02:42:28.027 回答