class MyLog < ApplicationRecord
has_one_attached :xlsx_file
end
I create .xlsx file as email attachments:
xlsx = render_to_string layout: false, template: "dir/template"
xlsx_base64 = Base64.encode64(xlsx)
attachment = {mime_type: Mime[:xlsx], content: xlsx_base64, encoding: 'base64'}
attachments["file.xlsx"] = attachment
And also I want add this file to MyLog table as attachment:
MyLog.create(
xlsx_file: xlsx
)
But xlsx is a string and it's not working. In the usual example attachable file came from file_field tag with ActionDispatch::Http::UploadedFile class and it's working. How can I attach my newly created with calsx .xlsx file to my record?
CodePudding user response:
A way to accomplish this without using an uploaded file is the .attach
function (docs).
Example:
xlsx = render_to_string layout: false, template: "dir/template"
log = MyLog.create
log.xlsx_file.attach(io: StringIO.new(xlsx), filename: 'file.xlsx', content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
You could also replace StringIO.new(string_content)
with File.open(filename)
if you were reading from the filesystem.