在Rails中显示多目录图片及Wrapbootstrap模板图片引用问题
Hey there, let's work through this problem step by step. It's super common when integrating external templates into Rails—since Rails uses the asset pipeline, we need to adjust how we reference files to play nice with it.
1. Fixing Image Paths
Your instinct to move the images into assets/images is right on the money. Here's how to do it cleanly:
- Create a subfolder in
app/assets/imagescalledbuild, then move the entireimgfolder fromwelcome/buildinto it. So your image path becomesapp/assets/images/build/img/[your-images]. - Now, in your
index.html.erb, replace any hardcoded image paths with Rails' asset helper. For example:- Instead of
<img src="build/img/logo.png">, use:<img src="<%= asset_path('build/img/logo.png') %>" alt="Logo"> - The
asset_pathhelper will generate the correct URL that Rails' asset pipeline recognizes, even after precompilation for production.
- Instead of
2. Making Other Build Folder Files Recognized
The build folder's CSS, JS, and other assets aren't being picked up because Rails doesn't automatically look in welcome/build for assets. Let's fix that:
For CSS Files
- Move the
cssfolder fromwelcome/buildintoapp/assets/stylesheets/build. - If your template uses relative paths in CSS to reference images (like
background: url('../img/bg.jpg')), you'll need to adjust these. Rename your CSS files to.scss(e.g.,style.css→style.scss) so you can use Rails asset helpers inside them. Then update the path to:background: url('<%= asset_path('build/img/bg.jpg') %>'); - To include the CSS in your layout, add this line to
index.html.erb(or your application layout if you want it site-wide):<%= stylesheet_link_tag 'build/style', media: 'all' %>
For JavaScript Files
- Move the
jsfolder fromwelcome/buildintoapp/assets/javascripts/build. - Include the JS in your template with:
<%= javascript_include_tag 'build/script' %>
Update Asset Precompilation
To make sure these assets are compiled correctly for production, add this line to config/initializers/assets.rb:
Rails.application.config.assets.precompile += %w( build/**/* )
This tells Rails to precompile all files in the build subfolders of your assets directory.
3. Quick Check for Routing
From your rake route output, I see you have welcome_about mapped to /welcome/about, but your issue with welcome/build comes from Rails trying to route it to a controller action (which doesn't exist). By moving all build assets into the app/assets directory, we eliminate the need for that route entirely—assets will be served through the asset pipeline instead of a controller.
That should get your template loading all assets correctly! Let me know if you hit any snags along the way.
内容的提问来源于stack exchange,提问作者BV45

