link_to
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (10)
- 2.0.3 (21)
- 2.1.0 (38)
- 2.2.1 (8)
- 2.3.8 (0)
- 3.0.0 (-16)
- 3.0.9 (-4)
- 3.1.0 (1)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (5)
- 4.1.8 (1)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (5)
- 5.1.7 (-1)
- 5.2.3 (3)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (7)
- 7.1.3.2 (13)
- 7.1.3.4 (0)
- What's this?
link_to(name, options = {}, html_options = nil, *parameters_for_method_reference)
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 ActionController::Base#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. If nil is passed as a name, the link itself will become the name.
The html_options will accept a hash of html attributes for the link tag. It also accepts 3 modifiers that specialize the link behavior.
- :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, your should check for it in your controllers action by using the request objects 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.
link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?" link_to "Help", { :action => "help" }, :popup => true link_to "View Image", { :action => "view" }, :popup => ['new_window_name', 'height=300,width=600'] link_to "Delete Image", { :action => "delete", :id => @image.id }, :confirm => "Are you sure?", :method => :delete
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" %>
link_to some url with current params
Code example
link_to "some text", users_path(:params => params, :more_params => "more params")
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" # => <a href="http://foo.bar" target="_blank">External link</a>
Anchor tag in link_to
Code example
link_to("some text", articles_path(:anchor => "comment"))
will output <a href = “/articles#comment” >some text
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</a>
The second is minimally documented, but as a hash, can accept multiple values and is perhaps a little cleaner
link_to with block (Edge Rails)
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 %> <strong>Awesome link</strong> -- 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
:confirm, :popup, and :method override :onclick
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 # => <a href="#" onclick="if(confirm('Are you sure?')) {destroyJsFunction()}; return false;">Delete</a> # actual output # => <a href="#" onclick="return confirm('Are you sure?');">Delete</a>
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.
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'
Text and Image together in #link_to
Code Example
link_to “Hello World #{ image_tag(‘web/worl.png’) }”.html_safe, some_path
: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
<a href="some_obj/id" data-confirm="Are you sure?" data-method="delete">Delete</a>
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).
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))
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’) %>
Using fontawesome icons inside link_to
<%= link_to (‘<i class=“fa fa-thumbs-up fa-lg”> </i>’).html_safe, vote_path(@image)%>
in this way you can use thumbs-up icon instead of usual text such as “like” in link_to
Link with relative url
By default link_to opens url as absolute if path does not contain http:// or https:// For Ex.
link_to ‘View’, “test123.abc.com/ag/acf”, target: :_blank, title: “Click to open url in a new tab”
Then it’ll open the link with absolute path not only with test123.abc.com/ag/acf.
If link_to path contains http:// then it takes the relative url.
link_to ‘View’, “http://test123.abc.com/ag/acf”, target: :_blank, title: “Click to open url in a new tab”
Now it open the relative url as it contains.
: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.