Rails5+神社多文件上传
Rails 5 + Shrine multiple files upload
我正在尝试使用多态关联和 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
我可以在查看文档后保存照片。
请告知如何在可成像范围内验证图像的唯一性。
我知道可以为每个原始版本生成一个签名,但这是正确的方法吗?
谢谢
生成签名是判断两个文件是否具有相同内容而不将这两个文件加载到内存中的唯一方法(您应该始终避免)。此外,使用签名意味着如果将签名保存到列中,则可以使用数据库唯一性约束 and/or 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
我正在尝试使用多态关联和 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
我可以在查看文档后保存照片。
请告知如何在可成像范围内验证图像的唯一性。
我知道可以为每个原始版本生成一个签名,但这是正确的方法吗?
谢谢
生成签名是判断两个文件是否具有相同内容而不将这两个文件加载到内存中的唯一方法(您应该始终避免)。此外,使用签名意味着如果将签名保存到列中,则可以使用数据库唯一性约束 and/or 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