0
0
RailsHow-ToBeginner · 3 min read

How to Use link_to in Rails: Syntax and Examples

In Rails, use the link_to helper to create HTML links easily by passing the link text and the URL or path. For example, link_to 'Home', root_path generates a clickable link to the home page.
📐

Syntax

The link_to helper creates an HTML anchor tag. It takes at least two arguments: the link text and the URL or path. You can also pass an optional hash of HTML options like CSS classes or data attributes.

  • link text: The text shown for the link.
  • URL or path: Where the link points to, like a route helper or a string URL.
  • HTML options: Optional settings like class, id, or data attributes.
ruby
link_to 'Link Text', url_or_path, html_options = {}
💻

Example

This example shows how to create a link to the home page with some styling and a data attribute. It demonstrates the basic usage and how to add HTML options.

erb
<%= link_to 'Home', root_path, class: 'btn btn-primary', data: { toggle: 'tooltip', placement: 'top' }, title: 'Go to Home' %>
Output
<a class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Go to Home" href="/">Home</a>
⚠️

Common Pitfalls

Common mistakes include:

  • Passing a string URL without quotes or with wrong syntax.
  • Forgetting to use path helpers like root_path or post_path(@post).
  • Not escaping HTML in link text when needed.
  • Misusing HTML options by passing them as a string instead of a hash.
erb
<!-- Wrong: missing quotes around URL -->
<%= link_to 'Google', 'https://www.google.com' %>

<!-- Right: URL as string -->
<%= link_to 'Google', 'https://www.google.com' %>
📊

Quick Reference

UsageDescription
link_to 'Text', pathBasic link with text and path
link_to 'Text', url, class: 'btn'Link with CSS class
link_to 'Delete', post_path(@post), method: :delete, data: { confirm: 'Are you sure?' }Link that sends DELETE request with confirmation
link_to image_tag('logo.png'), root_pathLink with an image instead of text

Key Takeaways

Use link_to with link text and a path or URL to create links in Rails views.
Pass HTML options as a hash to add classes, data attributes, or other HTML attributes.
Always use path helpers like root_path or post_path for internal links.
Wrap URLs in quotes when passing strings to link_to.
Use link_to with method and data options for actions like delete with confirmation.