I have some images in the public folder, I obtain the url /public/link/to/image.jpg
in my controller. I want to display it in my view, so I passed the url to the view.
But how can I display it on the webpage?
I searched through the post, most of them related to photos stored in assets folder,
whichi can be retrieved by <%= image_tag image-url (filename) %>
in view.
So how could I display image in public folder in view?
There are some pre-built gems that allow this to be done fairly quickly, but it’s also good for practice to roll your own. Let’s see how we can create some static pages in our own fresh Rails application.
But what about all the static images you have in your web application? background images, buttons, icons - they too should be delivered through a Rails CDN, offloading their delivery from your servers and improvixng your website's performance.
You can always do it yourself - setup your cloud environment, upload all these static images to your cloud storage, access them through a Rails CDN and make sure to update these images when they change. Or - you can let Cloudinary do it. Automatically. In this post we wanted to introduce a new Cloudinary feature.
Alternatively, just create it yourself using the command line: And place the following in the app/controllers/pages_controller.rb file: That will set up an empty show action in our controller. The show action in the pages controller will be what we use to render our static page.
I just tested this out in one of my applications, adding an image to the public folder, and was able to render it in view by using:
<img src="/your_image_file_name.png">
I've never done it through the public folder before, but if I had to guess I'd say you don't need the "/public" part of the file path.
If I understand the question, that should do it - hope to have helped.
You can also use Rails-way via <%= image_tag("/path/to/file.jpg") %>
For security reasons, image_tag
can only look inside /public
, so you don't have to specify /public
in the path — it will get added automatically.
Remark - try always to store images in subfolders in /public
as it (image_tag) will not work if you omit /public
and simply pass the image filename to image_tag
, like <%= image_tag("filename.jpg") %> <- in this case it will go search /assets/images
folder.
Solution in action:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With