How to Use link_to in Ruby on Rails



In this article, you will learn how to use link_to in Ruby on Rails.

How to use link_to

The link_to method is a helper method provided by Ruby on Rails to create HTML links in your views. Here’s how to use it:

link_to(body, url, html_options = {})
  • body: The text that will be displayed as the link
  • url: The URL that the link should point to
  • html_options (optional) : A hash of additional HTML attributes you want to include in the link tag.
<%= link_to "Click here", "/welcome/index" %>

This will create an HTML link with the text “Click here” that points to the URL “/welcome/index”.

You can also use named routes instead of the URL string. For example, if you have a named route called “welcome”, you can use it like this:

<%= link_to "Click here", welcome_path %>

To add additional HTML attributes to the link, you can pass them as a hash to the html_options parameter. For example, to add a CSS class to the link, you can do:

<%= link_to "Click here", "/welcome/index", class: "button" %>

The link_to method can also accept a block, which allows you to create more complex links with custom HTML. For example:

<%= link_to "/welcome/index" do %>
  <span class="glyphicon glyphicon-home"></span> Home
<% end %>

This will create an HTML link with a custom icon and text, using Bootstrap’s glyphicon CSS classes.