max bröker
max bröker

Reputation: 21

Rails: Image as a link

I want to make a link in my nav bar. The problem is that I want an image as the clickable link. So (click on image -> next Site) this is the code I use now for linking with the site.

<a class="nav" <%= link_to "Home", posts_path %> </a>

Upvotes: 2

Views: 7327

Answers (4)

Promise Preston
Promise Preston

Reputation: 28920

If you're using Active Storage on Rails, you could do this:

Say, you have a model named Product and an attributed named image:

For the Index page

<%= link_to product do %>
  <%= image_tag(product.image, class: 'product-image__img') if product.image.attached? %>
<% end %>

OR

<%= link_to(product) do %>
  <%= image_tag(product.image, class: 'product-image__img') if product.image.attached? %>
<% end %>

For the Show page

<%= image_tag(@product.image, class: 'product-image__img') if @product.image.attached? %>

Upvotes: 0

Bonface Mudiri
Bonface Mudiri

Reputation: 3

<a class="navbar-brand" href="/" style="float:none">
    <%= image_tag "yourlogo.png", width:150 %> 
</a>

Upvotes: 0

Oskar Holmkratz
Oskar Holmkratz

Reputation: 145

<%=link_to(image_tag("the_best_image_path.jpg", class: "img_class_goes_here"), posts_path, class: "navbar-brand"%>

Upvotes: 1

idmean
idmean

Reputation: 14875

You can provide a block to link_to

<%= link_to posts_path do %>
   <%= image_tag "image" %>
<% end %>

Upvotes: 8

Related Questions