23 May

Infer name with link_to - Rails Tricks Issue 8


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:

e64c5264-b936-4296-8245-4fc6a337d1b0.png 36.7 KB 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: d2dae7c6-f1a0-4876-ab44-db492a3a96cf.png 73.7 KB 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:

3f3b14aa-c0c6-413a-992d-b38d3e81fd26.png 33.7 KB

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

5999a45b-1f1d-434c-9286-2415cab3838f.png 24.9 KB 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.