我试图从Rails表单中附加的Paperclip文件中保存absolute_path
。我想将它保存到数据库中供以后使用。
我通过Paperclip文档阅读,无法找到我认为可行的任何内容。 Ruby在ruby-docs中有一个文件抽象解决方案,我可以在终端中工作,但我不确定如何使用Rails和Paperclip在表单中实现它。
最终,目标是解析XML文件并使用文件路径告诉Paperclip在哪里可以找到XML中列出的位于同一文件夹中的图像。
我有2个型号BulkImport和BulkDownloads。 BulkImport解析xml文件并在BulkDownloads中创建每个下载。
XML剪辑:
<?xml version="1.0"?>
<CUSTOMERS>
<CUSTOMER>
<FIRST_NAME>FIRST</FIRST_NAME>
<LAST_NAME>LAST</LAST_NAME>
<EMAIL>TEST@TESTEMAIL.COM</EMAIL>
<CUSTOMER_ID>222222</CUSTOMER_ID>
<WEB_PASSWORD>1234567</WEB_PASSWORD>
<GALLERY_CODE>CODE</GALLERY_CODE>
</CUSTOMER>
</CUSTOMERS>
BulkImports模型:
class BulkImport < ActiveRecord::Base
require "open-uri"
has_many :bulk_downloads, dependent: :destroy
has_attached_file :doc
validates_attachment_content_type :doc,
presence: true,
content_type: ["application/xml",
"text/xml"],
message: "file must be in xml file format"
def parse_file
tempfile = File.open("#{doc.path}")
file = Nokogiri::XML(tempfile)
parse_xml(file)
end
def parse_xml(file)
file.root.elements.each do |node|
if node.node_name.eql? 'CUSTOMER'
tmp_download = BulkDownload.new
tmp_download.cust_id = node.xpath("CUSTOMER_ID").text
tmp_download.webpassword = node.xpath("WEB_PASSWORD").text
img = node.xpath("CUSTOMER_ID").text
## THIS IS THE PATH I WANT TO CUSTOMIZE BASED ON XML FILE LOCATION
image_url = URI.parse("app/xml/#{img}.jpg").to_s
tmp_download.attachment = open(image_url)
tmp_download.save!
self.bulk_downloads << tmp_download
end
save
end
end
end
BulkImport控制器创建操作:
def create
@bulk_import = BulkImport.new(bulk_import_params)
respond_to do |format|
if @bulk_import.save
@bulk_import.parse_file
format.html { redirect_to bulk_imports_path, notice: "#{@bulk_import.bulk_downloads.count} downloads were successfully created." }
format.json { render :show, status: :created, location: @bulk_import }
else
format.html { render :new }
format.json { render json: @bulk_import.errors, status: :unprocessable_entity }
end
end
end
我在save之前尝试过queued_for_write [:original] .path,它返回xml doc的tmp文件路径而不是原始url。
2.2.1 :007 > doc = bi.doc.queued_for_write[:original]
=> Paperclip::FileAdapter: testfile.xml
2.2.1 :008 > doc.path
=> "/var/folders/b_/6d4jhyxn0yd9mvv2bzvc67nw0000gn/T/9bc955dbd052ef51652e70a5104492e320150629-38408-m0q0zm.xml"