Sunday, September 6, 2009

Rails Basics : link_to

It is an almost Rails convention that you should use Ruby code rather than HTML to create links as a mater of style and flexibility via routes.rb

link_to is an example of a Rails function  for html generation and is typically used to add site-wide navigation. For example,

   <%= link_to('Home',       { :action = 'index'}) %> |
   <%= link_to('About Us', { :action ='about'}) %>

You may be interested to note that curly braces are optional in hashes where they are the final argument to a function as follows :-

   <%= link_to('About Us',:action ='about') %>

How does one not link to a page that is currently displayed ?

   <%= link_to_unless_current('Home',       { :action = 'index'}) %> |
   <%= link_to_unless_current('About Us', { :action ='about'}) %>

Are there other related link_to functions ?

Rails adheres to a naming convention whereby a group of related functions have related names, usually of the form original_function_name and original_function_name_with_modification

Let's check to the Rails API via the Rails API Tab in Aptana Radrails or  at http://api.rubyonrails.org and this is what you should find

  • link_to
  • link_to_if
  • link_to_remote
  • link_to_unless
  • link_to_unless_current
How to display an image inside a link_to

<%= link_to image_tag("about.gif", :border=>0), :action => 'about' %>

1 comment:

iterology said...

Should be :action => 'index', not :action = 'index'

Welcome to Rails.. Rails... Rails !

In 1995, I started the popular Clipper...Clipper... Clipper website (no blogs then) which was very popular and linked by virtually every Clipper-related site. When I switched to Windows via Delphi in 1997, I started the Delphi... Delphi... Delphi site. In June 2007, I discovered Ruby on Rails and no prize for guessing what I am gonna name this blog. which I started on 2nd October 2007.

As at 10th June 2010, we have 13,364 unique visitors from more than 84 countries such as Angola, Andorra, Argentina, Australia, Austria, Algeria,Barbados, Bosnia and Herzogovina, Belgium, Brazil, Bulgaria, Bangladesh, Belarus, Bolivia, Chile, Cambodia, Cape Vede, Canada, China, Colombia, Costa Rica, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Estonia, Finland, France, Guadeloupe, Guatemala, Germany, Greece, Hong Kong, Hungary, India, Indonesia, Ireland, Israel, Italy, Japan, Kenya, Korea, Lithuania, Latvia, Malaysia, Mexico, Macao, Netherlands, Nepal, Norway, New Zealand, Oman, Panama, Peru, Poland, Portugal,Paraguay , Philippines, Romania, Russian Federation, Saudi Arabia, Singapore, Spain, Slovakia, Slovenia, Serbia, South Korea, Slovenia, South Africa, Spain, Switzerland, Sri Lanka, Sweden, Taiwan, Thailand, Turkey, United Arab Emirates, Ukraine, USA, UK, Venezuela, Vietnam

CCH
10th June 2010, 19:42