Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display static image in public folder (rails 4)

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?

like image 979
Timothy Leung Avatar asked Oct 19 '14 03:10

Timothy Leung


People also ask

Is it possible to create static pages in a Rails application?

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.

Should all static images be delivered through a rails CDN?

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.

How do I upload static images to Cloudinary?

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.

How do I render a static page in a controller?

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.


2 Answers

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.

like image 59
Jonathan Bowman Avatar answered Nov 06 '22 01:11

Jonathan Bowman


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:

  1. enter image description here

  2. enter image description here

like image 35
Andrius Avatar answered Nov 06 '22 02:11

Andrius