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:
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:
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:
| REST verb
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
<%=. 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="http://www.url.com/model_instance">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') %>