Ruby on Rails中图片无法加载的问题求助
Hey there, I’ve run into this exact problem before— let’s get your images loading properly step by step.
First, let’s break down why you’re seeing the No route matches [GET] "/images/image.jpg" error: Rails’ asset pipeline doesn’t serve images directly from /images/ by default; it processes assets from app/assets/images and serves them from the /assets/ path instead. Here’s how to fix it:
Double-check your image’s location
Make sureimage.jpgis actually saved inapp/assets/images/(not a subfolder unless you specify it, likeimage_tag 'subfolder/image.jpg'). Also, watch out for filename capitalization— Rails is case-sensitive, soImage.jpgwon’t matchimage.jpg.Fix your configuration settings
In newer Rails versions (4+),config.serve_static_assetshas been replaced withconfig.public_file_server.enabled. Update yourconfig/environments/development.rbfile to:config.public_file_server.enabled = true config.assets.compile = trueYou don’t need to modify
production.rbright now since you’re working locally.Restart your Rails server
This is crucial! Any changes to config files won’t take effect until you stop and restart your server (Ctrl+Cthenrails sagain).Use the correct
image_tagsyntax
Your original<%= image_tag 'image.jpg' %>is the right approach— Rails should automatically generate the correct path (like/assets/image.jpg) once the pipeline is working. If you want to verify the asset path manually, you can use:<%= image_tag asset_path('image.jpg') %>Avoid hardcoding paths like
<img src="/assets/images/image.jpg">— the asset pipeline handles fingerprinting and path resolution for you, so hardcoding can lead to broken links later.Precompile assets (optional but helpful for development)
Run this command in your terminal to precompile your assets into thepublic/assetsfolder:rails assets:precompileThen restart your server. This forces Rails to process and serve the compiled assets directly, which can resolve odd pipeline glitches.
If you’ve followed all these steps and still have issues, check if you have any custom routes that might be interfering with the /assets/ path— but in most cases, the above steps should get your images loading correctly.
内容的提问来源于stack exchange,提问作者Agruis

