Search code examples
ruby-on-railsasset-pipelineassets

Subdirectories and the Rails assets pipeline


I have this directory structure in my project:

- assets
-- images
--- game
--- avatars

I reference an image in avatars in code like this:

image_tag('avatar.png')

In development this works, in production I'm getting an error.

I have this code in application.rb

Dir.glob("#{Rails.root}/app/assets/images/**/").each do |path|
  config.assets.paths << path
end

When I compile my assets in development I see they are being created in public, under their subdirectories. So like this:

- public
-- assets
--- game
--- avatars

But in the log I'm seeing this:

http://demo1e97.lvh.me:3000/assets/avatar-edc80241a6bae07d6ed70cdffef15753.png

So it isn't using the subdirectory there.

What is the best way to solve this so it works both in development and in production? Should all the images be written into one directory in public, or should I include the subfolder when referencing the images?


Solution

  • You should always include the relative path (under assets/images) when referencing the image, like this:

    <%= image_tag("avatars/avatar.png") %>
    

    That will resolve to the file located at app/assets/images/avatars/avatar.png and will ensure it works in all environments. You can then completely remove this code from application.rb:

    Dir.glob("#{Rails.root}/app/assets/images/**/").each do |path|
      config.assets.paths << path
    end