robinmanz
robinmanz

Reputation: 471

Rails: what is the url to an image hosted in assets?

I have an image hosted on my rails server in the assets folder, I'd like to access this image through an url rather than using the path so that I can display it in my react component.

How can I find the url for said image so that when I go to the url the image will be displayed?

Upvotes: 1

Views: 3649

Answers (3)

arieljuod
arieljuod

Reputation: 15848

Rails' assets pipeline creates a digest of each asset and adds that to the filename, so the name is not always the same, you can't just copy it and use it forever (you can make rails recreate all the digests and all the urls are changed for example).

I can think of few options:

1 - Disable the assets pipeline digest feature On your environment's config file, add config.assets.digest = false and now the name won't have the digest at the end. Read the docs though, since the digest is there for a reason, you can disable it but it's better to decide that after reading the doc.

https://guides.rubyonrails.org/asset_pipeline.html#turning-digests-off

2 - Move those images to /public If you move the images to /public, they won't be compiled by the assets pipeline.

3 - Use a gem like non-stupid-digest to select which assets should have it https://rubygems.org/gems/non-stupid-digest-assets lets you configure some assets to prevent the assets pipeline to skip the digest generation without turning off the feature for all the assets

4 - Let the assets pipeline alone and put the urls somewhere on your html To get the correct current path of an image, you can use the helper image_path (for example: image_path('something.png') returns /assets/something-123...890.png). You can then write that on your template like:

<script>
  imageUrl = '<%= image_url('something.png') %>';
</script>

And you'll have access to that imageUrl variable on your javascript code.

Upvotes: 1

Jake
Jake

Reputation: 1186

As far as I know, you will need to go into your public folder and then to assets.

Find the image you want and then copy it's name.

You will need to call it like: /assets/img-name-033cce876b38fb47072fb3668a5.jpg or /assets/folder/ before the image name if it's in another folder and so on.

Upvotes: 0

Davis Roberto
Davis Roberto

Reputation: 47

You have to use image_tag. If you have "image.png" in your assets, you can use

<%= image_tag "image.png" %>

and it will result in a URL like this

/assets/image-bb14d53a12ca1aa006defb5c0f0923aa3c946f7e2dfd534846b3a1d3b8aac72e.png

When using image_tag, Rails creates a random token for image authentication. You can't just use <img src="/assets/image.png because there is no token.

Upvotes: 1

Related Questions