0
0
Ruby on Railsframework~5 mins

Link and URL helpers in Ruby on Rails

Choose your learning style9 modes available
Introduction

Link and URL helpers make it easy to create links and URLs in your Rails app without typing full paths. They keep your code clean and safe.

When you want to create a clickable link to another page in your app.
When you need to generate a URL for redirecting users.
When you want to link to a specific resource like a user or article.
When you want to keep your links working even if routes change.
When you want to add query parameters or anchors to URLs easily.
Syntax
Ruby on Rails
link_to 'Link Text', path_or_url, html_options = {}
url_for(options = {})

link_to creates an HTML link (<a> tag) with text and a path or URL.

url_for generates a URL string based on options or objects.

Examples
Creates a link with text 'Home' pointing to the root page.
Ruby on Rails
link_to 'Home', root_path
Creates a link to a user's profile with a CSS class for styling.
Ruby on Rails
link_to 'Profile', user_path(@user), class: 'profile-link'
Generates the URL for showing the article with ID 5.
Ruby on Rails
url_for(controller: 'articles', action: 'show', id: 5)
Creates a link to the search page with a query parameter.
Ruby on Rails
link_to 'Search', search_path(query: 'rails')
Sample Program

This example shows how to use link_to to create a button linking to a new article form and a list of article titles linking to each article's page.

Ruby on Rails
class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end
end

# In app/views/articles/index.html.erb
<%= link_to 'New Article', new_article_path, class: 'btn btn-primary' %>
<ul>
  <% @articles.each do |article| %>
    <li>
      <%= link_to article.title, article_path(article) %>
    </li>
  <% end %>
</ul>
OutputSuccess
Important Notes

Always use path helpers (like article_path) instead of hardcoding URLs to keep links flexible.

You can add HTML options like classes, IDs, or data attributes to link_to for styling and behavior.

Use url_for when you need just the URL string without creating a link tag.

Summary

Link and URL helpers help you create links and URLs easily and safely in Rails.

Use link_to for clickable links and url_for to get URL strings.

They keep your app flexible and your code clean.