0

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 に伝えるにはどうすればよいですか?

4

1 に答える 1

1

あなたのvalidates_attachment_content_type定義は間違っていると思います。:content_typeオプションにハッシュを渡すのではなく、単一のコンテンツ タイプまたはタイプの配列を渡す必要があります。

あなたの場合、次のようにする必要があります。

validates_attachment_content_type :fax_document, 
       content_type: ["application/pdf", "application/octet-stream"] 
于 2016-05-09T18:50:37.577 に答える