user1977201
user1977201

Reputation: 61

Rails: how to assign a link to image

I need to make images in page linkable. My code is:

<%= image_tag p.photos.first.avatar.url(:small) if p.photos.size > 0 %>

How to make this linkable?

Tried doing this:

<%= link_to (image_tag p.photos.first.avatar.url(:small) if p.photos.size > 0), product_path(p.id) %>

But gives syntax error.

Any one?

Upvotes: 0

Views: 91

Answers (2)

jvnill
jvnill

Reputation: 29599

change the link to use the block form (for better readability)

<%= link_to product_path(p.id) do %>
  <% if p.photos.any? %>
    <%= image_tag(p.photos.first.avatar.url(:small)) %>
  <% else %>
    <div>Default text for the link if the image is not present</div>
  <% end %>
 <% end %>

Upvotes: 2

davidb
davidb

Reputation: 8954

<%= link_to image_tag(p.photos.first.avatar.url(:small)).html_safe, product_path(p.id) if p.photos.size > 0%>

Upvotes: 1

Related Questions