Search code examples
imagetagspackruby-on-rails-6webpacker

Rails 6, webpacker: image_pack_tag renders wrong image path, adds "assets/" to URI


Working with new Rails 6 app using webpacker. Images are stored in /app/frontend/images.

//added to /app/frontend/application.js

const images = require.context('../images', true)
const imagePath = (name) => images(name, true)

Webpacker config:

/config/webpacker.yml contains:
default: &default
  source_path: app/frontend
  source_entry_path: packs
  public_root_path: public
  public_output_path: packs
  cache_path: tmp/cache/webpacker
  check_yarn_integrity: false
  webpack_compile_output: true

MY PROBLEM: image_pack_tag incorrectly adds assets/ to image path.

<%= image_pack_tag 'media/images/AdminLTELogo.png', alt: 'AdminLTE Logo', class: "brand-image img-circle elevation-3", style: "opacity: .8" %>

Renders... <img alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8" src="/assets/%2Fpacks%2Fmedia%2Fimages%2FAdminLTELogo-28f7e31d41f353b3aaff1236c7108479.png">

Removing assets/ from the path will successfully render the image.

Any ideas what could be adding assets/ to the image path?


Solution

  • THE CAUSE: Just prior to this error I had created a model called 'asset'. Somehow the resources :assets function in my routes.rb file conflicted with the image_pack_tag, inserting assets/ in the path for all images. I realized this when I simply commented out the resources :assets line in my routes.rb file, and all the images loaded properly.

    THE SOLUTION: I namespaced my asset model and also namespaced the resources :assets line in my routes.rb file. All images load correctly now.