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
<%= 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With