【问题标题】:Rails 5 + Shrine multiple files uploadRails 5 + Shrine 多个文件上传
【发布时间】:2017-10-26 04:30:20
【问题描述】:

我正在尝试使用多态关联和 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

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

【问题讨论】:

    标签: ruby-on-rails ruby shrine


    【解决方案1】:

    生成签名是判断两个文件是否具有相同内容的唯一方法,而无需将这两个文件都加载到内存中(应始终避免)。此外,使用签名意味着如果您将签名保存到列中,您可以使用数据库唯一性约束和/或 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 直接上传。 :)
    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2015-09-30
    • 2017-04-24
    相关资源
    最近更新 更多