我有一个现有文件的目录,我需要将其作为遗留迁移的一部分迁移到我的 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 手动上传的正确方法是什么?
感谢任何帮助。
最佳答案
试试这个
@attachments.each do |attachment|
begin
options = {
:project_id => attachment.ProjectID,
:name => attachment.Description,
:user_id => attachment.UserId,
:created_at => attachment.CreatedDate,
:updated_at => attachment.LastModifiedDate,
:file => File.new(File.join("/home/username/Attachments/",attachment.Filename))
}
new_attachment = Attachment.new(options)
new_attachment.save!
puts "Attachment added successfully "
rescue => error
puts "Error migrating Attachment: #{error}"
end
end
也许这对你有用,因为 carrierwave 会在内部为你调用 store!
问题?
Failed to manipulate with rmagick, maybe it is not an image? Original Error: no decode delegate for this image format
不知道你想在这里做什么,因为你已经定义了一个 image?
方法,它没有在条件中指定也是你想要 content_type
的东西只出现在 image
文件中
如果 no
可能只有进程调用会起作用
进程:set_content_type
如果 是
那么也许你必须做这样的事情
process :set_content_type , :if => :image?
def image?(new_file)
%w(jpg jpeg gif).include?(new_file.extension)
end
希望对你有帮助
根据评论编辑
试试这个只是使用条件相同的逻辑
version :thumb ,:if => image? do
// your code
end
关于ruby - 在 Carrierwave 中手动上传和保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17978905/