link_to
link_to(name = nil, options = nil, html_options = nil, &block)Creates an anchor element 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, which generates an anchor element that uses the value of the String as the href for the link. Using a :back Symbol instead of an options hash will generate a link to the referrer (a JavaScript back link will be used in place of a referrer if none exists). If nil is passed as the name the value of the link itself will become the name.
Signatures
link_to(body, url, html_options = {}) # url is a String; you can use URL helpers like # posts_path link_to(body, url_options = {}, html_options = {}) # url_options, except :method, is passed to url_for link_to(options = {}, html_options = {}) do # name end link_to(url, html_options = {}) do # name end link_to(active_record_model)
Options
-
:data - This option can be used to add custom data attributes.
Examples
Because it relies on url_for, link_to supports both older-style controller/action/id arguments and newer RESTful routes. Current Rails 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>
When name is nil the href is presented instead
link_to nil, "http://example.com" # => <a href="http://www.example.com">http://www.example.com</a>
More concise yet, when name is an Active Record model that defines a to_s method returning a default value or a model instance attribute
link_to @profile # => <a href="http://www.example.com/profiles/1">Eileen</a>
You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
<%= link_to(@profile) do %> <strong><%= @profile.name %></strong> -- <span>Check it out!</span> <% end %> # => <a href="/profiles/1"> <strong>David</strong> -- <span>Check it out!</span> </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&baz=quux">Nonsense search</a>
You can set any link attributes such as target, rel, type:
link_to "External link", "http://www.rubyonrails.org/", target: "_blank", rel: "nofollow" # => <a href="http://www.rubyonrails.org/" target="_blank" rel="nofollow">External link</a>
Turbo
Rails 7 ships with Turbo enabled by default. Turbo provides the following :data options:
-
turbo_method: symbol of HTTP verb - Performs a Turbo link visit with the given HTTP verb. Forms are recommended when performing non-GET requests. Only use data-turbo-method where a form is not possible.
-
turbo_confirm: "question?" - Adds a confirmation dialog to the link with the given value.
Consult the Turbo Handbook for more information on the options above.
Examples
link_to "Delete profile", @profile, data: { turbo_method: :delete } # => <a href="/profiles/1" data-turbo-method="delete">Delete profile</a> link_to "Visit Other Site", "https://rubyonrails.org/", data: { turbo_confirm: "Are you sure?" } # => <a href="https://rubyonrails.org/" data-turbo-confirm="Are you sure?">Visit Other Site</a>
14Notes
Link to caller URL
link_to "Back", :back
Link to same URL with different format
Use +params+.+merge+ as options. Ex.
<%= link_to "RSS feed", params.merge(:format => :rss), :class => "feed_link" %>
Opening a link in a new window
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
==== 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
==== Example
link_to name, url, :popup => ['dialog name','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes']
Anchor tag in link_to
HTML5 data- attributes using RESTful approach
HTML5 specifies extensible attributes like data-foo="bar" (or as in Twitter Bootstrap data-toggle="modal"), which poses two problems for Rails.
First, if you're using symbol notation in link_to to specify attributes, this fails (dash is not a valid symbol character), so === Invalid! link_to "Edit", @user, :class => "btn", :data-toggle => "modal"
There are two solutions:
- put the symbols in quotes,
- use the special +:data+ hash
=== Solution 1: Quote Symbols link_to "Edit", @user, :class => "btn", "data-toggle" => "modal"
=== Solution 2: Use the :data hash link_to "Edit", @user, :class => "btn", :data => {:toggle => "modal"}
=== Resulting HTML <a href="/users/1" class="btn", data-toggle="modal">Edit
The second is minimally documented, but as a hash, can accept multiple values and is perhaps a little cleaner
Remember to sanitize name
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
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'
:method => :delete, etc.
If you're upgrading to Rails 3 you'll need to make sure you include rails.js (which is in public/javascripts when you rails new someproject) You'll need to include it after prototype. And you'll need to have a 1.7 version of prototype.
When you do a link_to "Delete", @some_obj, :method => "delete", :confirm => "Are you sure?"
Rails 3 will generate Delete
rails.js will creates observers that convert that into a form.
Be aware that this probably won't work as a link from inside a form (since forms in forms isn't valid).
Text and Image together in #link_to
Code Example
link_to "Hello World #{ image_tag('web/worl.png') }".html_safe, some_path
:popup gotcha in IE
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
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
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))