我需要将数据库表中的所有产品生成到 XML 文件中。因为我的应用程序在 Heroku 上运行,所以我需要使用 Amazon S3 作为存储。
这是一个关于如何保存图像的例子:
has_attached_file :photo,
:styles => {
:thumb=> "100x100#",
:small => "400x400>" },
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => "/:style/:id/:filename"
这让我有点困惑……因为我不确定这个任务的逻辑。
我的想法是在 Products
Controller 中运行一个操作(比如 create_xml_feed
)
xml = Builder::XmlMarkup.new( :indent => 2 )
xml.instruct! :xml, :encoding => "ASCII"
xml.product do |p|
p.name "Test"
end
但问题来了 - 我不知道如何将新创建的文件保存到 Amazon S3 Bucket 中。
我会很感激每一次进步,谢谢
最佳答案
首先,创建一个事件记录类来保存您上传的 XML 文件。在此之后,您可以编写逻辑来创建您的 xml 字符串,通过首先创建 XmlUploader 类的新实例来创建一个新文件,然后创建您想要的 xml 字符串,将其保存在一个文件中,然后将此文件分配为附件文件.保存后,您的 xml 文件将上传到 s3。
class XmlUploader < ActiveRecord::Base
has_attached_file :uploaded_file, :storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => "/:id/:filename"
def create_uploaded_file
xml = ::Builder::XmlMarkup.new( :indent => 2 )
xml.instruct! :xml, :encoding => "ASCII"
xml.product do |p|
p.name "Test"
end
file_to_upload = File.open("some-file-name", "w")
file_to_upload.write(xml)
file_to_upload.close()
self.uploaded_file = File.open("some-file-name")
self.save!
end
end
class CreateXmlUploaders < ActiveRecord::Migration
def change
create_table :xml_uploaders do |t|
t.attachment :uploaded_file
t.timestamps
end
end
end
xml_file = XmlUploader.new
xml_file.create_uploaded_file
关于ruby-on-rails - Rails - 如何创建文件 (XML) 并将其保存到 Amazon S3 存储桶中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13369777/