2017-05-25 59 views
1

我想用多态关联和神社实现多个文件上传。Rails 5 +神殿多个文件上传

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 

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

回答

1

生成签名是判断两个文件是否具有相同内容而不将这两个文件加载到内存(您应该始终避免)的唯一方法。此外,使用签名意味着如果将签名保存到列中,则可以使用数据库唯一性约束和/或ActiveRecord唯一性验证。

这是你可以如何与靖国神社做到这一点:

# 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 
+0

谢谢!我计算了最后一天使用jQuery进行直接上传。 :) – Anton