pete
pete

Reputation: 2799

How to make image_tag hyperlink using link_to in Rails, with mouseover?

I am placing *image_tag* images within *link_to* elements, as well as trying to do a mouseover image swap. It's all working except for the mouseover, which is not grabbing the alternate image. On a more general note, am I doing hyperlinked images correctly? Sorry, new to Rails. Much appreciated!

<%= link_to (image_tag("#{product.prod_img}.jpg", alt: product.prod_name, class: 'img_prod_thumb', mouseover: "#{product.prod_img}_over.jpg")), "/products/#{product.id}" %>

Upvotes: 0

Views: 633

Answers (1)

user419017
user419017

Reputation:

Couple of pointers:

  1. Don't dynamically add img extensions to your code (esp. in the view) unless there is a very good reason to do so(?)
  2. You can use simple product as the path, instead of a hardcoded url

Here's what I'd do:

>>> move product image name construction to the model, helper, or decorator
# model (for simplicity)

def prod_img_full
  "#{prod_img}.jpg"
end

def prod_img_over
  "#{prod_img}_over.jpg"
end

>>> update and clean up link_to

<%= link_to image_tag(product.prod_img_full, 
            alt: product.prod_name, 
            class: 'img_prod_thumb', 
            mouseover: product.prod_img_over), 
            product %>

You could easily move the image_tag to a decorator, which would allow this within your views:

<%= link_to product.hover_image, product %>

Upvotes: 1

Related Questions