簡體   English   中英

Ruby on Rails中文件的意外行為

[英]Unexpected behaviour with a file in Ruby on Rails

嘗試在Ruby on Rails中上傳文件時,遇到一個問題。

這是我上傳文件的方式:

def upload_image(image)
  File.new(Rails.root.join('assets','images','products',image.original_filename),'wb') do |f|
    f.write(image.read)
  end
end

引發異常:

Errno::ENOENT in ProductsController#update

No such file or directory - /home/alex/RubymineProjects/psg/assets/images/products/my-image.png

為什么會這樣呢? 我只是在創建一個新文件,不是在嘗試打開現有文件。

它不會創建目錄。

File.new("test", 'wb') #=> creates the file test
File.new("test/test", 'wb') #=> test.rb:1:in `initialize': No such file or directory - test/test (Errno::ENOENT)

如果添加/ app,則具有您要查找的路徑。 不過,不要真的以為這就是使用資產管道的方式。 請參閱此問題中的推理。

File.open(Rails.root.join('app','assets','images','test.jpg'),'wb') do |f|
  f.write("image")
end
 => 5

cat app/assets/images/test.jpg #=> image% 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM