I have a rake task that fetches XML documents and saves them to a model in my app. The task worked until I added validation of content_type to the model
The task now gives the error:
Datafile content type is invalid, Datafile is invalid
How can i set the tmp file's content_type to text/xml so that the validation passes?
The task code is below:
task :fetch_documents => :environment do
Net::FTP.open("www.example.com", "xxxxx", "xxxxx") do |ftp|
ftp.nlst.each do |file_name|
tmp = Tempfile.new(['foo', '.xml' ])
ftp.gettextfile(file_name, tmp.path)
# save it
document = Document.new
document.file_name = File.basename(file_name)
document.datafile = tmp
document.save!
tmp.close
end
end
end
I was able to find out the content-type to use like this:
gem install mime-types
and added to my rake task:
require 'mime/types'
I then broke into the pry repl and used
MIME::Types.type_for(tmp.path).first.content_type
which enabled me to add the correct mime type to the model validation:
application/xml
I'm not sure why the files are application/xml when the form uploaded files are text/xml but in hindsight, a pretty obvious fix!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With