Alex Reisner
Alex Reisner

Reputation: 29427

Asset Subdirectories in Rails 3.1

I have a Rails 3.1 app with an image:

app/assets/images/icons/button.png

It seems like the image should be served at this URL:

assets/icons/button.png

but if I go to this URL I get a 404. To fix this I created an initializer and added my images/icons subdirectory to the asset path:

Rails.application.assets.append_path "app/assets/images/icons"

However, this does not seem like it can possibly be the recommended way to accomplish this. I'm aware of the require and require_tree directives for JavaScript and CSS assets, is there an equivalent for image assets? How are other people doing this?

Upvotes: 2

Views: 2429

Answers (1)

Piotrek Okoński
Piotrek Okoński

Reputation: 597

EDIT: As of Rails 3.2.rc1 this is now fixed! asset_path now generates proper paths when deploying to sub-uri!

For images it just works. Rails packages everything in images/ tree. I personally use them like this (actual code):

CSS:

a#icon-followers{
  background:  url(<%= asset_data_uri "icons/followers.png" %>) center center no-repeat;
}

(asset_data_uri actually makes the images inline in the CSS file using base64, but that's irrelevant in this case)

No custom configuration required. After precompiling, images from app/assets/icons/ end up in public/assets/icons/.

You can open public/assets/manifest.yml to see how Rails translates the paths to actual files.

Upvotes: 2

Related Questions