Scope

You’re using Ruby on Rails and the Twitter Bootstrap framework. You are using the link_to ActionView helper method. The generated anchor will be visually represented in a navbar as a Bootstrap button component (via the ‘btn’ and ‘btn-small’ class attributes). Finally, you want to use one of those sweet Boostrap icons instead of text. It should look something like this:

[caption id=”attachment_427” align=”aligncenter” width=”412”]RNOC Action Bar RNOC Action Bar[/caption]

The Problem

I had difficulty understanding the correct way to call the link_to method to get the results I desired. Part of my failure to grok is because I’m a complete newbie to RoR, and the other part of it is because the link_to method has 4 distinct signatures that you can call it by.

After some searching around I found a couple of resources on Stack Overflow which looked promising:

However, none of those results were quite exactly what I was looking for. They did provide some useful insight into solving the problem though.

Solution

Here’s the code:

https://gist.github.com/5497304

Explanation

If my understanding is correct, then this approach implements the third link_to method signature: link_to(options = {}, html_options = {}) do 

The options parameter we give here is a hash which is passed to the url_for method, and finally to the Route Module. It ends up returning a URL string in the form of http://yoursite/pages/new

The html_options parameter describes the attributes (other than href) which we desire present in the generated anchor. In this example we are describing an anchor with two classes: btn and btn-small. You could add additional symbols to the hash just as easily: {:class => ‘btn btn-small’, :id => ‘new-page-button’, :title => ‘Create A New Page’}

Finally, the way we’re calling link_to requires that we pass it a block to use as the generated link body (or in our case, icon). So we escape from the ERB sequence for a moment, enter the HTML which Boostrap turns into an icon, and then close the block.