【问题标题】:"No such file or directory @ rb_sysopen" when converting a file to a string将文件转换为字符串时“没有这样的文件或目录@rb_sysopen”
【发布时间】:2015-10-16 03:01:04
【问题描述】:

我尝试像这样读取文本文件:

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 的影响。

我尝试手动粘贴文件路径,但收到同样的错误。

【问题讨论】:

    标签: ruby-on-rails string file text directory


    【解决方案1】:

    消息“没有将 Paperclip::Attachment 隐式转换为字符串”告诉您 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)

    【讨论】:

      猜你喜欢
      • 2014-05-14
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 2014-07-09
      • 2018-05-01
      • 2019-03-22
      相关资源
      最近更新 更多