1
我有一個現有文件的目錄,我需要遷移到我的Rails應用程序作爲傳統遷移的一部分。基本上我需要手動上傳這些文件並在數據庫中爲它們保存一條新記錄。我還沒有找到正確的方法來做到這一點。目前我已在在rake任務如下:手動上傳並保存在Carrierwave中的文件
@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
attachment.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手動上傳它的正確方法是什麼?
任何幫助表示讚賞。
謝謝。其實,我看起來並不再需要'形象'?方法,所以我刪除它。即使在實施更改後,我仍然會收到上述錯誤。我也嘗試刪除'process set_content_type',仍然是同樣的錯誤。如何防止rmagick處理'doc'和文本文件? – Drew
@德魯檢查編輯回答 – Viren
它的工作!謝謝,你是一個拯救生命的人。 – Drew