Paperclip gem (4.3.6) を使用して、サード パーティの API からファイルをストリーミングし、HTTP 応答の本文を、Fax を表す ActiveRecord モデルの添付ファイルとして使用したいと考えています。
class Fax
has_attached_file :fax_document
validates_attachment_content_type :fax_document, content_type: { content_type: ["application/pdf", "application/octet-stream"] }
end
以下のコードを使用して、API サーバーから HTTP 応答を取得し、それを添付ファイルとして Fax モデルに保存しています。(以下のコードは、簡潔にするためにわずかに変更されています)。
#get the HTTP response body
response = download(url)
#add the necessary attributes to the StringIO class. This technique is demonstrated in multiple SO posts.
file = StringIO.new(response)
file.class.class_eval { attr_accessor :original_filename, :content_type }
file.original_filename = "fax.pdf"
file.content_type = 'application/pdf'
#save the attachment
fax = Fax.new
fax.fax_document = file
fax.save
このresponse
変数には、pdf バイナリ オブジェクトの文字列表現のように見えるものが含まれておりfax.save
、content_type が無効であるというエラーが発生します。を使用してファックス モデルのペーパークリップ検証を明示的に緩和するdo_not_validate_attachment_file_type :fax_document
と、添付ファイルは適切に保存されます。
返されたコンテンツが実際に「application/pdf」であることを認識できないため、Paperclip コンテンツ タイプの検証が失敗していると思われます。
Paperclip で content_type not valid エラーが発生するのはなぜですか? 応答の本文が PDF であることを Paperclip に伝えるにはどうすればよいですか?