method

link_to

link_to(name, options = {}, html_options = nil)
public

Creates a link tag of the given name using a URL created by the set of options. See the valid options in the documentation for url_for. It’s also possible to pass a string instead of an options hash to get a link tag that uses the value of the string as the href for the link, or use :back to link to the referrer - a JavaScript back link will be used in place of a referrer if none exists. If nil is passed as a name, the link itself will become the name.

Options

  • :confirm => 'question?' - This will add a JavaScript confirm prompt with the question specified. If the user accepts, the link is processed normally, otherwise no action is taken.
  • :popup => true || array of window options - This will force the link to open in a popup window. By passing true, a default browser window will be opened with the URL. You can also specify an array of options that are passed-thru to JavaScripts window.open method.
  • :method => symbol of HTTP verb - This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified. Useful for having links perform a POST operation in dangerous actions like deleting a record (which search bots can follow while spidering your site). Supported verbs are :post, :delete and :put. Note that if the user has JavaScript disabled, the request will fall back to using GET. If you are relying on the POST behavior, you should check for it in your controller’s action by using the request object’s methods for post?, delete? or put?.
  • The html_options will accept a hash of html attributes for the link tag.

Note that if the user has JavaScript disabled, the request will fall back to using GET. If :href => '#' is used and the user has JavaScript disabled clicking the link will have no effect. If you are relying on the POST behavior, your should check for it in your controller’s action by using the request object’s methods for post?, delete? or put?.

You can mix and match the html_options with the exception of :popup and :method which will raise an ActionView::ActionViewError exception.

Examples

Because it relies on url_for, link_to supports both older-style controller/action/id arguments and newer RESTful routes. Current <a href="/rails/Rails">Rails</a> style favors RESTful routes whenever possible, so base your application on resources and use

  link_to "Profile", profile_path(@profile)
  # => <a href="/profiles/1">Profile</a>

or the even pithier

  link_to "Profile", @profile
  # => <a href="/profiles/1">Profile</a>

in place of the older more verbose, non-resource-oriented

  link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
  # => <a href="/profiles/show/1">Profile</a>

Similarly,

  link_to "Profiles", profiles_path
  # => <a href="/profiles">Profiles</a>

is better than

  link_to "Profiles", :controller => "profiles"
  # => <a href="/profiles">Profiles</a>

Classes and ids for CSS are easy to produce:

  link_to "Articles", articles_path, :id => "news", :class => "article"
  # => <a href="/articles" class="article" id="news">Articles</a>

Be careful when using the older argument style, as an extra literal hash is needed:

  link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article"
  # => <a href="/articles" class="article" id="news">Articles</a>

Leaving the hash off gives the wrong link:

  link_to "WRONG!", :controller => "articles", :id => "news", :class => "article"
  # => <a href="/articles/index/news?class=article">WRONG!</a>

link_to can also produce links with anchors or query strings:

  link_to "Comment wall", profile_path(@profile, :anchor => "wall")
  # => <a href="/profiles/1#wall">Comment wall</a>

  link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
  # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

  link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
  # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

The three options specfic to link_to (:confirm, :popup, and :method) are used as follows:

  link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
  # => <a href="http://www.rubyonrails.org/" onclick="return confirm('Are you sure?');">Visit Other Site</a>

  link_to "Help", { :action => "help" }, :popup => true
  # => <a href="/testing/help/" onclick="window.open(this.href);return false;">Help</a>

  link_to "View Image", @image, :popup => ['new_window_name', 'height=300,width=600']
  # => <a href="/images/9" onclick="window.open(this.href,'new_window_name','height=300,width=600');return false;">View Image</a>

  link_to "Delete Image", @image, :confirm => "Are you sure?", :method => :delete
  # => <a href="/images/9" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form');
       f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
       var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
       m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete Image</a>

14Notes

Link to caller URL

dmantilla · Oct 1, 200815 thanks
link_to "Back", :back

Link to same URL with different format

hannu · Jul 4, 200813 thanks

Use +params+.+merge+ as options. Ex.

<%= link_to "RSS feed", params.merge(:format => :rss), :class => "feed_link" %>

Opening a link in a new window

zoopzoop · Oct 20, 20088 thanks

Use "_blank", not "_new" to open a link in a new window. link_to "External link", "http://foo.bar", :target => "_blank" # => External link

link_to some url with current params

bansalakhil · Jan 9, 20098 thanks

==== Code example

link_to "some text", users_path(:params => params, :more_params => "more params")

Window open a dialog of no menu, no status, have scroll

RobinWu · Jul 4, 20086 thanks

==== Example

link_to name, url, :popup => ['dialog name','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes']

link_to with block (Edge Rails)

james · Jul 25, 20086 thanks

New ability in Edge Rails to use link_to called with a block, e.g. The following is a view example:

<% link_to some_path do %> Awesome link -- it's pretty awesome <% end %>

This change was made in: http://github.com/rails/rails/commit/8190bce8bc7249b7b9f3680195336eb3ca9508ee

Patch in yourself, or likewise you can use the following snippet (which is the new link_to method with modifications [there are also Array extensions on edge to provide .second, .third etc which aren't present]).

==== url_helper_extensions.rb

module ActionView module Helpers module UrlHelper def link_to(*args, &block) if block_given? options = args.first || {} html_options = args[1] concat(link_to(capture(&block), options, html_options)) else name = args.first options = args[1] || {} html_options = args[2]

       url = case options
         when String
           options
         when :back
           @controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
         else
           self.url_for(options)
         end
   
       if html_options
         html_options = html_options.stringify_keys
         href = html_options['href']
         convert_options_to_javascript!(html_options, url)
         tag_options = tag_options(html_options)
       else
         tag_options = nil
       end
   
       href_attr = "href=\\"#{url}\\"" unless href
       "<a #{href_attr}#{tag_options}>#{name || url}</a>"
     end
   end
 end

end end

Anchor tag in link_to

bansalakhil · Feb 18, 20096 thanks

==== Code example

link_to("some text", articles_path(:anchor => "comment"))

will output some text

Remember to sanitize name

ville · Feb 17, 20092 thanks

While useful when in need of richer markup inside a link, the name parameter isn't sanitized or escaped and thus should be escaped when its content can't be guaranteed to be safe.

E.g. link_to(url, url)

may cause problems with character entities if url contains ampersands.

===== Correct usage

link_to(h(url), url)

This applies to all dynamic content.

Expression

r13 · Mar 19, 20092 thanks

You can put some expression too. For example for I18n (using haml on view):

some_locale.yml

links:
contacts: "My contacts"

index.html.haml

= link_to "#{t "links.contacts"}", :action => 'contacts'

:confirm, :popup, and :method override :onclick

metavida · Jul 26, 20102 thanks

upplying any combination of +:confirm+, +:popup+, and/or +:method+ options to the link_to method results the +:onclick+ option being overridden.

Example: link_to "Delete", '#', :confirm=>"Are you sure?", :onclick=>"destroyJsFunction()" # expected output # => Delete # actual output # => Delete

Note that the actual output doesn't include any mention of the "destroyJsFunction()" passed to the link_to method.

Rails 3 will use unobtrusive JavaScript, and I haven't tested how that will interact with the +:onclick+ option.

Text and Image together in #link_to

ShrutiGupta · Sep 3, 20151 thank

Code Example

link_to "Hello World #{ image_tag('web/worl.png') }".html_safe, some_path

:popup gotcha in IE

bquorning · Sep 7, 2009

If your popup title contains spaces or escaped HTML characters, Internet Explorer (at least 6/7) will not pop up a new window but open the link in the existing browser window.

logic in class/id

Graffzon · Nov 10, 2011

If you need to place some simple logic in class or like that, I think that best to make it with simple brackets:

====Code example

<%= link_to 'All actions', switch_action_tab_path, :remote => true, :class => ('selected' if @tab == 'all') %>

link_to with :as routing

danwich · Jan 16, 2012

The following will not work when your post model is routed with the :as option: link_to("View post", @post) Instead, use the helper with your custom name: link_to("View post", :url => renamedpost_path(@post))