How to create links in Rails

Creating links can be confusing if you are just starting to learn Rails. It is important to understand how your views, controllers, and routes are connected.

If you already have an app you are working on, simply type:

$rake routes

This command will let you see all your routes, how your views connect to your controller, their URLs, and how to link them in your HTML.erb file.

For example, this is mine:
rake routes rails

The ‘Prefix’ column contains the name of the link path that you will use.

The ‘Verb’ column tells you what HTTP actions are connected to each path:

Action show create update destroy

The ‘URI Pattern’ column is the URL link

The ‘Controller#Action’ column gives you the name of the controller and the name of the method action connected with the page.

Taking the above information, we can open our ‘views/articles/index.html.erb’ page and start adding links!

Before you start, it is important to understand the difference between <% and <%=. The difference is:

  • <%..%> is for items you DO NOT want to appear in the view (like if statements and iterations).
  • <%=..%> is for items you DO want to appear in the view (like images and links).

To create a link in your html.erb file, you can follow this example:

<%= link_to "Text to show", model_instance %>

It will generate html that looks like this:

<a href="">Text to show</a>

Let’s create our own using the routes listed in our $rake routes using the above example.

<% link_to "New Article", new_article_path %>

The HTML for the link will look like so:

<a href="/articles/new">New Article</a>

To add a class to the link, just include it at the end:

<% link_to "New Article", new_article_path, class: "btn btn-default" %>

To add an image, use the following code recipe:

<%= image_tag('image.jpg') %>

One thought on “How to create links in Rails

  1. Pingback: How to create links in Rails | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s