Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to convert <img src= > to image_tag in rails app

This is my first post here and it might sound awfully stupid. Im building my first rails app.

I have this line in my index.html.erb

    <img src="/assets/rand_front/<%= @random_image%>", style='height:50vw;width:100vw;margin-bottom:20px;' >

I want to use image_taginstead of the img src

What is the correct way to wrap it around the code?

So far I've tried <%= image_tag ( "/assets/rand_front/<%= @random_image%>", style='height:50vw;width:100vw;margin-bottom:20px;') %>

and <%= image_tag ( "/assets/rand_front/<%= @random_image%>"), style='height:50vw;width:100vw;margin-bottom:20px;' %>

and many other versions, but none seems to work, what am I doing wrong? and how should I write it properly?

this <%= @random_image%> bit is taking this variable from the index method in the controller.

def index
   @products = Product.all.order(created_at: :desc).group_by(&:category_id)
    @images  = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg"]
    @random_no = rand(10)
    @random_image = @images[@random_no]
end
like image 324
Slowboy Avatar asked Sep 28 '16 12:09

Slowboy


2 Answers

<%= image_tag "rand_front/#{@random_image}", style: 'height:50vw;width:100vw;margin-bottom:20px;' %>

image_tag will automatically add assets at start of the path

check Image Tag for Documentation

like image 196
Qaisar Nadeem Avatar answered Oct 20 '22 22:10

Qaisar Nadeem


If I am not mistaken you have a rand_front folder in your assets folder so you should call image_tag("#{@random_image}") since by default the image_tag helper should check all the folders in the assets directory for the image name

For the CSS properties you can consider using the options hash which would allow you to pass in the CSS properties as keys with your desired values

image_tag("#{@random_image}", height: 20, width: 20) You can check out the documentation in the previous answer

like image 22
Black Enigma Avatar answered Oct 20 '22 23:10

Black Enigma