Rails: Why images are not showing in my rails basic app

后端 未结 4 1582
遥遥无期
遥遥无期 2020-12-30 03:44

my index.html.erb code -

Listing products

<% @products.each do |product| %>
4条回答
  •  抹茶落季
    2020-12-30 03:54

    I just checked your application, there is nothing wrong with your code. The only thing is to understand how image_tag works.

    Usually you put all your images, javscripts and stylesheests on the app/assets directory. When you work on the development environment, those files are served uncompressed, but when you deploy to production, the assets are precompiled, minified, and the result files are stored in public/assets.

    The idea behind minified assets, is just to make the requests faster for the clients, and to save bandwidth.

    Now, on the method image_tag, you can use an external path for the image, a local path for the image or a relative path for the image.

    When you do

    <%= image_tag "http://www.mywebsite.com/image.jpg" %>
    

    it will use the absolute url for the image tag, and you will end with

    
    

    You can add a local path as well, like

    <%= image_tag "/images/image.jpg" %>
    

    Which will end in

    
    

    which is actually the issue you are having, because rails, when it precompiles the files, it puts everything within /public/assets, and you can access those files by going to the path /assets as the other users explained.

    So the code

    <%= image_tag "/assets/image.jpg" %>
    

    actually works, because you end with

    
    

    The other thing you can do, is to use a relative path, i.e.

    <%= image_tag "image.jpg" %>
    

    that will be converted to

    
    

    and that will work the same the last scenario.

    Nevertheless, on your application, you are going to let the users to upload their own images, this will happen later when you advance on the book, on a real world app, you will use a gem like paperclip or carrierwave

提交回复
热议问题