2015-10-16 36 views
0

我試圖讀取一個文本文件,像這樣:「沒有這樣的文件或目錄@ rb_sysopen」當文件轉換成字符串

file = File.read(record.file) 

和收到的錯誤no implicit conversion of Paperclip::Attachment into String

所以我就追加to_s最終將其轉換爲字符串:

text = File.read(record.file.to_s) 

和我收到的錯誤No such file or directory @ rb_sysopen

我知道這個文件和目錄存在的事實,因爲我有一個重定向到文件的錨標記,並且這不受在末尾附加to_s影響。

我嘗試手動粘貼文件路徑,但我收到了同樣的錯誤。

回答

1

消息「Paperclip :: Attachment into String隱式轉換」告訴您File.read需要一個字符串,但您傳入的參數(record.file)爲Paperclip::Attachment。您需要的是獲取與該附件對象關聯的路徑的方法。

Paperclip::Attachment的源代碼,我看到its to_s method returns a URL。將URL傳遞到File.read會導致找不到文件錯誤,因爲File.read需要路徑。簡而言之,您將file://foo/bar傳遞給僅需要/foo/bar的方法。

我注意到the path method returns a path on the file system(除非該附件被存儲在S3),所以嘗試:

file = File.read(record.file.path)

相關問題