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:
![](https://pombomailer.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MzUsInB1ciI6ImJsb2JfaWQifX0=--fcb712a021e2dc1c718588e6b5503756a556cc75/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--cefc62acd607acb36c209b04aa5893ccc86cdf29/e64c5264-b936-4296-8245-4fc6a337d1b0.png)
![](https://pombomailer.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MzYsInB1ciI6ImJsb2JfaWQifX0=--ef89bdc8c1cda3d7b586bb24f25ccd422d634132/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--cefc62acd607acb36c209b04aa5893ccc86cdf29/d2dae7c6-f1a0-4876-ab44-db492a3a96cf.png)
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:
![](https://pombomailer.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MzcsInB1ciI6ImJsb2JfaWQifX0=--a39ac99b8dd918e8c40ef71750c7237638cc06f9/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--cefc62acd607acb36c209b04aa5893ccc86cdf29/3f3b14aa-c0c6-413a-992d-b38d3e81fd26.png)
Now let’s say in your application a user can specify the URL for their blog and you pass that to link_to:
![](https://pombomailer.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MzgsInB1ciI6ImJsb2JfaWQifX0=--7636b65802c764c4381f9fee85723dd58f38147b/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--cefc62acd607acb36c209b04aa5893ccc86cdf29/5999a45b-1f1d-434c-9286-2415cab3838f.png)
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.