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/imagesfolder, so Rails can't find them. - Forgetting to add the file extension or using the wrong file name.
- Not providing
alttext, 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
| Option | Description | Example |
|---|---|---|
| source | Image file name or path | 'photo.jpg' |
| alt | Alternative text for accessibility | alt: 'User photo' |
| class | CSS classes for styling | class: 'rounded' |
| size | Width and height in 'WxH' format | size: '200x150' |
| title | Tooltip text on hover | title: '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.