A very basic question, but somehow I can't get it to work. I am trying to have an image located in the project's local folder to display on Rails. Additionally, I am using bootstrap; thus I need to declare class: "img-responsive"
as well. Here is the original code: <img class="img-responsive" src="assets/img/mockup/img2.jpg" alt="">
I have consulted this post which suggested <%= image_tag("xyz.png", class: "img-responsive img-thumbnail img-circle") %>
and rubyonrails guide which suggested image_tag("/icons/icon.gif", class: "menu_icon")
.
I have tried
<%= image_tag ("assets/img/mockup/img2.jpg", class: "img-responsive")%>
and
<%= image_tag "assets/img/mockup/img2.jpg" %>
But it still does not work. I can confirm that the path is: app/assets/img/mockup/img2.jpg
How can I display the said image on rails app view?
You have two options:
1) Move your img
folder contents to app/assets/images
and then reference the image like:
<%= image_tag ("mockup/img2.jpg", class: "img-responsive")%>
2) Add your img
folder to the Rails assets path search in the file config/application.rb
config.assets.paths << Rails.root.join("app", "assets", "img")
This happens because app/assets/img/
is not included by default in the rails assets search path.
For more info check http://guides.rubyonrails.org/asset_pipeline.html#asset-organization
I was browsing and saw this SO post . I was able to get it work using
<%= image_tag ("/assets/mockup/img2.jpg"), class: "img-responsive"%>
Image path was assets/images/mockup/img2.jpg
; omitting images
from the image path assets/mockup/img2.jpg
solves the issue.
Just to add to Iggy's answer
I had this challenge when working on a Rails 6 application with Bootstrap 4 .
You do not need to add your image directory to the Rails assets path search in config/initializers/assets.rb
My Image path was app/assets/images/products/product-16.jpg
.
That is the images were put in a products
directory under the images
directory.
I referenced it this way
<%= image_tag ('/assets/products/product-16.jpg'), class: 'product-image__img' %>
If you need to add a link to the image, then reference it this way:
<%= link_to image_tag('/assets/products/product-16.jpg'), 'http://#', target: '_blank', class: 'product-image__body' %>
This will result to this:
<a href="images/products/product-16.jpg" data-width="700" data-height="700" class="product-image__body" target="_blank">
</a>
That's all.
I hope this helps
Try this instead:
put your image in public folder, my below image path is public/image_folder/img_name
<img src="<%= "/image_folder/img_name" %>">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.