Timothy Leung
Timothy Leung

Reputation: 1465

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?

Upvotes: 24

Views: 34099

Answers (4)

Evolve
Evolve

Reputation: 9203

This still works all the way up to Rails 7.

Say you have two images asset_image.png and public_image.png saved respectivley under /app/assets/images and the other under /public.

You never need to include /assets or /public in the file paths in your code.

Images saved under /app/assets/images :

img_tag('asset_image.png')  # <== No leading slash; Looks in assets

Images saved directly under /public :

img_tag('/public_image.png') # <== Has a leading slash; Looks in Public

Upvotes: 9

Gediminas Šukys
Gediminas Šukys

Reputation: 7391

You can use:

<%= image_tag('/link/to/image.jpg') %>

if your image is in public dir, and link/to/ subdirs

If it is in root public folder:

<%= image_tag('/image.jpg') %>

Upvotes: 7

user3467734
user3467734

Reputation:

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

Upvotes: 10

Jonathan Bowman
Jonathan Bowman

Reputation: 1646

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.

Upvotes: 24

Related Questions