DEV Community

Jude
Jude

Posted on • Updated on

Ruby On Rails Beginners - Demystify the magic. Part 2: It's just a ruby method

Part 1 | Part 3

Following on from part 1, we are going to break down the link_to method. It's something you'll use almost as soon as you start working on a rails app, and it's fairly easy to understand.

The link_to method is referred to as a helper. A helper is just a ruby method that is available to use in Rails view files. Rails comes with built-in helpers, like link_to, but you can also create your own.

<%= link_to "Apple", "http://apple.com" %>
Enter fullscreen mode Exit fullscreen mode

or if you prefer to use parentheses

<%= link_to("Apple", "http://apple.com") %>
Enter fullscreen mode Exit fullscreen mode

Which will render out the following HTML code.

<a href="https://apple.com">Apple</a>
Enter fullscreen mode Exit fullscreen mode

To get an idea of what's going on here, we can recreate a basic version of the method ourselves.

def link_to(text, url)
   "<a href='#{url}'>#{text}</a>".html_safe
end
Enter fullscreen mode Exit fullscreen mode

And that it's. The built-in helper is more complex than this, but at it's most basic version this is all it does.

The built in helper can also take in a third argument, which is a hash where you can pass in HTML options, which you can learn more about here

In the next part we'll dive in to the rails api docs, and learn a little more about the link_to method.

Top comments (0)