问题
The problem
This code: image_url('my_image.png')
generates this url from within the view:
http://localhost:3000/assets/my_image-d229e5de55e4f8589c78e2419221fa3ae4f9d4026f.png
But when the same code is run from the controller, it generates this:
http://localhost:3000/images/my_image.png
Only the first url actually works. How can I generate the correct url (the one containing the fingerprint) from the controller?
What I tried
I found a way to make it work locally, by generating the digest manually.
This method generates the correct url
def make_image_url_with_fingerprint(image_path)
request.base_url + "/assets/" + Rails.application.assets.find_asset(image_path).digest_path
end
And to use it:
make_image_url_with_fingerprint('my_image.png')
=> http://localhost:3000/assets/my_image-d229e5de55e4f8589c78e2419221fa3ae4f9d4026f.png
However, this doesn't work in production, probably because the assets are already compiled and therefore there's nothing at Rails.application.assets.find_asset(image_path)
Other notes:
Similar question here: rails 4 not using digests in asset filenames, but only in production
I couldn't solve this in production after 9 hours. So I created a new S3 bucket, copied the image there, and reference it directly from it's S3 url. This is annoying since it skips all of the rails conventions (assets in one place, precompilation etc), but I needed a quick fix and can figure out a better solution in good time.
来源:https://stackoverflow.com/questions/65990841/image-url-gives-different-result-when-run-from-controller