When building an application in RoR, we may need some images on the web page. In RoR application images are stored in ‘public/images/’ folder and we need to embed those images in our view pages which contains the HTML tag.
I am working on the windows with ruby 1.9.2 and rails 3.0.1.
What I have done, for putting the images in the view page I have used the following code(Let us assume that a header.gif file is in the “public/images” directory).
<img src=”/images/header.gif” border = “0” class=’headerImg’ width = “200px” height=”75px” />
The above code worked fine. But some cases while loading the images, the server failed and broke down with a message http://localhost:3000/images/header.gif could not be found. And I had to start my server again and again. To fix this issue, I have used the image_tag provided by ruby. Please check the following code.
<%= image_tag(“header.gif”, :border => 0, :class => ‘headerImg’, :size => “200×75”) %>
At the run time, this image_tag creates the following code
<img width=”150″ height=”130″ src=”/images/header.gif?1279706442″ border = “0” class = “‘headerImg'” alt=”header” />
This fixed the server break down issue while loading the images in the web pages.
* If your images are placed in another directory in the public/images folder, for e.g. header.gif is in the “public/images/layout/” folder. Then to put the image in the web page use the following code.
<%= image_tag(File.join(“layout”,”header.gif”), :border => 0, :class => ‘headerImg’, :size => “200×75”) %>
For other examples related to image_tag, you can visit http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag.