marcel salathe
marcel salathe

Reputation: 252

asset_path in rails console on heroku for images

I'm using paperclip to deal with images.

To serve an image when none is provided by a user, I use the value provided by defaul_url, which is set to

ActionController::Base.helpers.asset_path('logo_medium.png')

This works fine locally: the src attribute of the image is set correctly.

On heroku, however, things break. The src attribute of the image has the value '/logo_medium.png', which is wrong.

Indeed, when I start up the rails console on heroku,

ActionController::Base.helpers.asset_path('logo_medium.png')

returns

/assets/logo_medium-f0bc5e00182468b861cf32c8c35595ce.png

which is correct.

I'm puzzled that the app seems to return something different from what the console does.

For the sake of completeness, my view uses

<%= image_tag @user.avatar.url(:medium) %>

Any help greatly appreciated.

Upvotes: 4

Views: 5099

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Asset Fingerprinting

When you deploy onto Heroku, you need to pre-compile your assets

This is important because pre-compiling fingerprints your assets, giving them a large hashed value at the end. The reason for this is:

Fingerprinting is a technique that makes the name of a file dependent on the contents of the file. When the file contents change, the filename is also changed. For content that is static or infrequently changed, this provides an easy way to tell whether two versions of a file are identical, even across different servers or deployment dates.

The fingerprinting is not a problem for Rails; it's the way you try and load those assets in the production environment. The asset pipeline is only really meant for styling, which means that if you're calling any assets, you need to be able to use dynamic methods to call them, such as image_path or asset_path

The way you do this with CSS is to use SCSS, and with javascript, it's append the .erb file type onto the JS filename. This allows you to use dynamic methods to call the assets you require, thus allowing you to use the fingerprinted files


Paperclip

You've included a Paperclip reference at the end of your question. Paperclip loads files through ActiveRecord, and doesn't touch the assets at all

Upvotes: 2

Related Questions