Rails development 模式加载不了 public 目录静态文件 (图片)

puma · May 16, 2018 · Last by IChou replied at May 17, 2018 · 1572 hits

报错信息

ActionController::RoutingError (No route matches [GET] "/public/uploads/registration/
user/avatar/21/52653c50-452b-42d0-a5ff-eca0195f1bd7.gif"):
select avatar from registration_users where id = 21;
                  avatar
------------------------------------------
52653c50-452b-42d0-a5ff-eca0195f1bd7.gif
(1 row)
ls public/uploads/registration/user/avatar/21
3d2384d5-2ae1-4472-9a4f-28566a05c053.gif 52653c50-452b-42d0-a5ff-eca0195f1bd7.gif

使用 CarrierWave 上传图片 在用 image_tag 显示的时候出现这个问题。 搜索了半天,找到可能相关的,enabled/disabled 了都不行😂

-Rails Guide

config.public_file_server.enabled configures Rails to serve static files from the public directory. This option defaults to true, but in the production environment it is set to false because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to true. Otherwise, you won't be able to use page caching and request for files that exist under the public directory.

puma closed this topic. 16 May 19:23
puma reopened this topic. 16 May 19:23

development 默认应该是可以加载静态文件的,production 可以交给 nginx 处理,但是本地开发怎么办😂

ruby version:    2.5.1
rails version:    5.1.6

add this to your config/environments/development.rb

config.public_file_server.enabled = true

@teddyinfi 😅 不行的,development 这一项默认为真。可能跟 rails 版本有关,我尝试下升级到 5.2

user.avatar_url 产生的字符串格式

/public/path/to/image

这里 serve public static file 是生效的,只是响应的是

http://localhost:3000/uploads/path/to/image

所以去掉前面的'/public'字符串即可

<%= image_tag user.avatar_url.sub(/^\/public/, '') if user.avatar %>

😐 这个只是我自己的解法,不知道大家有没有什么更好的办法

如果资源放在 public,意味着你是想自己管理资源文件并且不需要 rails 帮你做缓存控制,所以 assets 那一套 url/path 辅助方法就不能用了

所以,自己处理文件路径吧

get "/assets/:name" => redirect("/images/%{name}") ,:constraints => {:name => /.+/} if Rails.env.development?

非要用的话,改改这条路由可以处理你的情况

You need to Sign in before reply, if you don't have an account, please Sign up first.