我有一个现有文件的目录,作为遗留迁移的一部分,我需要将其迁移到我的 rails 应用程序中。基本上我需要手动上传这些文件并在数据库中为它们保存一条新记录。我还没有找到正确的方法来做到这一点。目前,我在 rake 任务中有以下内容:
@attachments.each do |attachment|
begin
new_attachment = Attachment.new
@attachment_file_path = "/home/username/Attachments/" + attachment.Filename
file = File.open(@attachment_file_path)
new_attachment[:file] = new_attachment.file.store!(file)
# Map old record fields to new
new_attachment.attributes = {
:project_id => attachment.ProjectID,
:name => attachment.Description,
:user_id => attachment.UserId,
:created_at => attachment.CreatedDate,
:updated_at => attachment.LastModifiedDate
}
new_attachment.save!
puts "Attachment added successfully "
rescue => error
puts "Error migrating Attachment: #{error}"
end
end
附件.rb
class Attachment < ActiveRecord::Base
mount_uploader :file, FileUploader
end
上传者:
class FileUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
include CarrierWave::MimeTypes
process :set_content_type
storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png pdf doc docx txt)
end
version :thumb do
process resize_to_fit: [152, nil]
end
def default_url
ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
end
protected
def image?(new_file)
if new_file.content_type == nil
return false
else
new_file.content_type.include? 'image'
end
end
end
这目前不起作用。该文件永远不会被上传,有时我会收到以下错误:
Failed to manipulate with rmagick, maybe it is not an image? Original Error: no decode delegate for this image format
在这种情况下,该文件是一个“.doc”文件。
打开本地文件并通过 Carrierwave 手动上传的正确方法是什么?
任何帮助表示赞赏。