Infer name with link_to - Rails Tricks Issue 8

23 May 2023

Hi, this week I want to tell you about an improvement coming in Rails 7.1. When you are using the link_to helper, it can infer the URL from the object you are passing to it as the second parameter:

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

Wouldn’t it be nice to infer the content of the a tag too? Thanks to Olivier Lacan, in Rails 7.1 that will be possible. You can specify what the text should be in the to_s method of the object, and you will only need to pass the object to the helper:

class Profile < ApplicationRecord
  def to_s
    name
  end
end

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

I love these small improvements to the framework.

While we are talking about link_to, I’d like to mention something about this helper. The second parameter accepts a string for the href attribute of the a tag. The HTML specification permits various protocols for that attribute, including javascript, so for instance, you can make a dummy link with the following:

link_to "I am not doing much", "javascript: void(0)"

Now let’s say in your application a user can specify the URL for their blog and you pass that to link_to:

link_to "Greg's Blog", @user.blog_url

This user can set the blog URL to javascript: XSS_PAYLOAD, and when someone clicks the link, the browser executes the JavaScript. To mitigate this issue, always validate the format of a URL your application accepts, especially if you intend to use it for linking to that URL.

That’s it for today. You may want to check out a post I wrote about a related topic about using link_to_if and link_to_unless to conditionally render a link in Rails.

Did you enjoy reading this? Sign up to the Rails Tricks newsletter for more content like this!

Or follow me on Twitter

Related posts