0
0
RailsHow-ToBeginner · 3 min read

How to Use image_tag in Rails: Syntax and Examples

In Rails, use the image_tag helper to display images in views by passing the image file name as a string, like image_tag('logo.png'). It generates an HTML <img> tag with the correct path to your asset. You can add options like alt text or CSS classes by passing a hash of options.
📐

Syntax

The basic syntax of image_tag is:

  • image_tag(source, options = {})

source: The image file name or path as a string.

options: A hash of optional HTML attributes like alt, class, size, etc.

ruby
image_tag('example.png', alt: 'Example image', class: 'img-responsive', size: '100x100')
Output
<img src="/assets/example.png" alt="Example image" class="img-responsive" width="100" height="100" />
💻

Example

This example shows how to use image_tag in a Rails view to display a logo with alternative text and a CSS class for styling.

erb
<!-- app/views/layouts/application.html.erb -->
<header>
  <%= image_tag('logo.png', alt: 'Company Logo', class: 'logo') %>
</header>
Output
<header> <img src="/assets/logo.png" alt="Company Logo" class="logo" /> </header>
⚠️

Common Pitfalls

Common mistakes when using image_tag include:

  • Not placing images in the app/assets/images folder, so Rails can't find them.
  • Forgetting to add the file extension or using the wrong file name.
  • Not providing alt text, which hurts accessibility.
  • Using incorrect option keys or values.

Always check your image path and options carefully.

erb
<!-- Wrong: missing file extension -->
<%= image_tag('logo') %>

<!-- Right: include file extension -->
<%= image_tag('logo.png') %>
Output
<!-- Wrong generates broken image link --> <!-- Right generates correct image tag -->
📊

Quick Reference

OptionDescriptionExample
sourceImage file name or path'photo.jpg'
altAlternative text for accessibilityalt: 'User photo'
classCSS classes for stylingclass: 'rounded'
sizeWidth and height in 'WxH' formatsize: '200x150'
titleTooltip text on hovertitle: 'Profile picture'

Key Takeaways

Use image_tag to easily add images in Rails views with correct asset paths.
Always provide descriptive alt text for accessibility.
Place images inside app/assets/images so Rails can find them.
Pass options as a hash to customize attributes like size, class, and title.
Check file names and extensions carefully to avoid broken images.