Question

The basic snippet of code I am trying to alter is:

<%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>

My question is: can the text 'Delete' be replaced to display an image which would perform the same action as to original code? i.e. replace 'Delete' with an image of an 'X'

I have tried:

<%= link_to 'img src="path_to_image"', post, method: :delete, data: { confirm: 'Are you sure?' } %>

Wasn't really expecting the code above to work, but I thought I would give it a shot. As expected it returned "a href="path_to_image"" in place of 'Delete'

Also thought I should add

rails -v
Rails 4.1.0
Was it helpful?

Solution

You can do it using image_tag helper:

<%= link_to post, method: :delete, data: {confirm: 'Are you sure?'} do %>
  <%= image_tag(your_image_url) %>
<% end %>

or, if you want to do it in one line:

<%= link_to image_tag(your_image_url), post, method: :delete, {confirm: 'Are you sure?'} %>

About your issue with path, since your image file seems to be placed in proper assets directory, this should work:

<%= link_to post, method: :delete, data: {confirm: 'Are you sure?'} do %>
  <%= image_tag('x_small_icon') %>
<% end %>

OTHER TIPS

Try this ,

<%= link_to image_tag('/img/img.png'), post, method: :delete, data: { confirm: 'Are you sure?' } %>

Nobody's actually pointed out quite why your original attempt doesn't work:

<%= link_to 'img src="path_to_image"', post, method: :delete, data: { confirm: 'Are you sure?' } %>

The reason is that the first argument to link_to is not a valid img tag - it's missing the < and >. Remember that the first argument is just including into the content of the resulting a tag as is, with no modifications. If you changed it to

<%= link_to '<img src="path_to_image">', post, method: :delete, data: { confirm: 'Are you sure?' } %>

then it would work. It's better to do what the other posters have suggested, which is to use a rails image_tag helper, but i thought someone should point out why your original code was broken rather than just tell you how to do it :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top