Skip to content

How to assign a css class or id to link_to method in Ruby on Rails

Posted on 06 May 2006

To assign a css class or id to a link_to method you do the following:

<%= link_to "Link name", { :controller => 'controller_name', :action => 'action_name' }, :class => 'someclass' -%>

The key part is seperating the :controller => and :action from the html using the curly brackets.

View the snippets archive ››

10 comments made

sal commented on 14 Jun 07 at 22:34

cheers :)

c0ureur commented on 25 Sep 07 at 10:04

thanks!

caius commented on 01 Dec 07 at 21:28

Thanks

Mike commented on 03 Dec 07 at 12:34

Thank you.

Ryan commented on 04 Dec 07 at 18:19

Not sure why this isn’t isn’t listed in the api site: http://api.rubyonrails.org but it does explain why you’re site was at the top of the list.. thanks!

zangra commented on 17 Dec 07 at 13:24

I would like to add a class to a single link. My problem is that I am getting those links from a loop:

< @links.each do |link| > < link_to link.name, {}, :class=>‘red’ > < end >

I would appreciate any help to do that? Thank you.

dreamthinker commented on 21 Feb 08 at 05:02

I tried a few times to tack in the class where I also have an image_tag inside the link_to … without luck so far..I’ll come back with an answer if I get there !

Paul commented on 21 Feb 08 at 05:09

This should work:

link_to(image_tag("image.gif"), { :controller => 'controller_name', :action => 'action_name' }, :class => 'someclass')
Kevin commented on 28 Feb 08 at 11:17

Thanks, that did it !

Francesco commented on 04 Jul 08 at 09:21

thank u very much…:)

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com